在我工作的地方,人们大多认为对象最好使用 C++ 风格的构造(带括号)来初始化,而原始类型应该使用 = 运算符来初始化:
std::string strFoo( "Foo" );
int nBar = 5;
不过,似乎没有人能够解释为什么他们更喜欢这种方式。我理解了std::string = "Foo";
效率会很低,因为它会涉及额外的副本,但是仅仅消除=
完全使用运算符并到处使用括号?
这是一个共同的约定吗?其背后的想法是什么?
使用 = 运算符或使用构造函数调用初始化变量在语义上是相同的,这只是风格问题。我更喜欢 = 运算符,因为它读起来更自然。
使用 = 运算符usually不生成额外的副本 - 它只是调用普通的构造函数。但请注意,对于非基本类型,这仅适用于与声明同时发生的初始化。比较:
std::string strFooA("Foo"); // Calls std::string(const char*) constructor
std::string strFoo = "Foo"; // Calls std::string(const char*) constructor
// This is a valid (and standard) compiler optimization.
std::string strFoo; // Calls std::string() default constructor
strFoo = "Foo"; // Calls std::string::operator = (const char*)
当您有重要的默认构造函数时,后一种构造可能会稍微低效。
The C++标准 http://www.parashift.com/c++-faq-lite/big-picture.html#faq-6.13,第 8.5 节第 14 段规定:
Otherwise (i.e., for the remaining copy-initialization cases), a temporary is created. User-defined conversion sequences that can convert from the source type to the destination type or a derived class thereof are enumerated (13.3.1.4), and the best one is chosen through overload resolution (13.3). The user-defined conversion so selected is called to convert the initializer expression into a temporary, whose type is the type returned by the call of the user-defined conversion function, with the cv-qualifiers
of the destination type. If the conversion cannot be done or is ambiguous, the initialization is ill-formed. The object being initialized is then direct-initialized
from the temporary according to the rules above.87) In certain cases, an implementation is permitted to eliminate the temporary by initializing the object directly; see 12.2.
第 12.2 节的一部分规定:
即使避免创建临时对象,也必须遵守所有语义限制,就像创建临时对象一样。 [例子:
即使不调用复制构造函数,也应满足所有语义限制,例如可访问性(11)。 ]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)