什么时候强制转换调用新类型的构造函数?

2021-12-31 00:00:00 casting c++

确定特定的 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.)

相关文章