且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当casts调用新类型的构造函数时?

更新时间:2022-06-27 00:20:47

每当创建一个新对象时,都会调用一个构造函数。 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".)

对于记录,用户定义的转换操作符可能是
call:

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 ) function
style cast( 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.)