初始化:括号与等号
有什么区别
T a(b);
和
T a = b;
和
T a = T(b);
?
推荐答案
T a( b );
是直接初始化,除非它被解析为函数声明,在这种情况下它是一个函数声明.
is direct initialization, unless it parses as a function declaration, in which case it's a function declaration.
T a = b;
是复制初始化,这意味着它就像在右侧构造一个临时对象一样工作,然后a
是复制构造的,或者在C中++11 及更高版本,可能从该临时移动构造.
is copy initialization, which means that it works as if a temporary object is constructed on the right hand side, and that a
is then copy constructed or, in C++11 and later, possibly move constructed, from that temporary.
编译器可以在可能的情况下自由地删除(删除)临时+复制/移动,但是复制或移动构造函数,无论在逻辑上使用哪个,都必须仍然是可访问的,而不是显式
.
The compiler is free to elide (remove) the temporary+copying/moving whenever it can, but a copy or move constructor, whichever would be logically used, must still be accessible and not explicit
.
例如,在 C++03 中,您不能复制初始化 std::ostringstream
,因为它没有复制构造函数.在 C++11 中,如果初始化程序是临时的,则可以复制初始化 ostringstream
,这会导致逻辑移动构造(但通常会被省略,优化掉).比如这个拷贝初始化声明,
For example, in C++03 you cannot copy-initialize a std::ostringstream
, because it doesn't have a copy constructor. In C++11 you can copy-initialize an ostringstream
if the initializer is a temporary, which then results in a logical move construction (which however will usually be elided, optimized away). For example, this copy initialization declaration,
ostringstream s = ostringstream( "blah" );
…不编译为 C++03,因为在 C++03 中,复制初始化调用了类的复制构造函数,而该构造函数不存在.然而,它确实编译为 C++11,因为在 C++11 中,复制初始化调用了移动构造函数.虽然(为了保持其作为流的错觉)std::ostringstream
不能直接复制,但它可以移动.
… doesn't compile as C++03, because in C++03 the copy initialization invokes the class' copy constructor, which doesn't exist. It does however compile as C++11, because in C++11 the copy initialization invokes the move constructor. And while (to maintain its illusion of being a stream) a std::ostringstream
can't be directly copied, it can be moved.
另一个这样的区别:在 C++03 中,只有复制初始化语法支持 花括号 初始化器,在 C++03 中,当 T
是聚合时可以使用它类型,例如原始数组.在 C++11 中,花括号符号已被扩展并概括为 统一初始化语法,因此它也可以用于直接初始化.所以下面直接初始化声明,
Another such difference: in C++03 only the copy initialization syntax supports curly braces initializer, which in C++03 you can use when T
is an aggregate type such as a raw array. In C++11 the curly braces notation has been extended and generalized as a uniform initialization syntax, so it can be used also with direct initialization. And so the following direct initialization declaration,
int v[]{ 3, 1, 4, 1, 5, 9, 2, 6, 5, 4 };
…不编译为 C++03,但编译为 C++11 及更高版本.
… does not compile as C++03, but does compile as C++11 and later.
=
复制初始化语法是 C 的原始初始化语法.
The =
copy initialization syntax is the original initialization syntax from C.
在 C++11 及更高版本中,由于移动语义,它可以用于比 C++03 更广泛的情况,例如与 std::ostringstream
.
And in C++11 and later, due to move semantics, it can be used in a much wider range of cases than in C++03, such as with a std::ostringstream
.
相关文章