当casts调用新类型的构造函数时? [英] When do casts call the constructor of the new type?

查看:110
本文介绍了当casts调用新类型的构造函数时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定特定static_cast是否会调用类的构造函数的规则是什么?

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".)

对于记录,用户定义的转换操作符可能是
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.)

这篇关于当casts调用新类型的构造函数时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆