When do casts call the constructor of the new type?(什么时候强制转换调用新类型的构造函数?)
问题描述
确定特定的 static_cast 是否会调用类的构造函数的规则是什么?c 风格/函数式风格转换怎么样?
What are the rules to determine whether or not a particular static_cast will call a class's constructor? How about c style/functional style casts?
推荐答案
每当创建新对象时,都会调用构造函数.static_cast
总是会产生一个新的临时对象(但请参阅 James McNellis 的评论)立即,或通过调用用户定义的转换.(但在为了返回所需类型的对象,用户定义转换运算符必须调用构造函数.)
Any time a new object is created, a constructor is called. A static_cast
always results in a new, temporary object (but see comment by James McNellis) either
immediately, or through a call to a user defined conversion. (But in
order to have an object of the desired type to return, the user defined
conversion operator will have to call a constructor.)
当目标是类类型时,C风格强制转换和函数风格根据定义,带有单个参数的强制转换与static_cast
.如果函数式风格转换有零个或多个参数,然后它会立即调用构造函数;用户自定义在这种情况下不考虑转换运算符.(一个可以质疑将其称为类型转换"的选择.)
When the target is a class type, C style casts and functional style
casts with a single argument are, by definition, the same as a
static_cast
. If the functional style cast has zero or more than one
argument, then it will call the constructor immediately; user defined
conversion operators are not considered in this case. (And one could
question the choice of calling this a "type conversion".)
作为记录,用户定义的转换运算符可能是称为:
For the record, a case where a user defined conversion operator might be called:
class A
{
int m_value;
public
A( int initialValue ) : m_value( initialValue ) {}
};
class B
{
int m_value;
public:
B( int initialValue ) : m_value( initialValue ) {}
operator A() const { return A( m_value ); }
};
void f( A const& arg );
B someB;
f( static_cast<A>( arg ) );
在这种特殊情况下,转换是不必要的,并且转换将在其缺席时隐式进行.但在所有情况下:隐式转换、static_cast
、C 风格转换 ((A) someB
) 或函数式样式转换 (A( someB )
),B::operator A()
将被调用.)
In this particular case, the cast is unnecessary, and the conversion
will be made implicitly in its absence. But in all cases: implicit
conversion, static_cast
, C style cast ((A) someB
) or functional
style cast (A( someB )
),
B::operator A()
will be called.)
这篇关于什么时候强制转换调用新类型的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么时候强制转换调用新类型的构造函数?
基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01