考虑C中的以下代码:
struct A {A(int);}; A foo() {return static_cast<A>(0);} A x = foo();
这里static_cast< A>(0)通过标准[5.2.9-4]创建一个临时对象,这是一个prvalue.标准[12.2-1]说
Temporaries of class type are created in varIoUs contexts: binding a reference to a prvalue (8.5.3),returning a prvalue (6.6.3),a conversion that creates a prvalue (4.1,5.2.9,5.2.11,5.4),throwing an exception (15.1),entering a handler (15.3),and in some initializations (8.5).
那么return语句也会再次创建一个临时对象?
顺便说一句,任何人都可以告诉我,标准是否保证隐式类型转换会创建一个临时对象?
解决方法
(§4/ 6)提到
The effect of any implicit conversion is the same as performing the corresponding declaration and initialization and then using the temporary variable as the result of the conversion.
所以是的,除非优化,应该创建一个临时应用程序,但我确信所有现代编译器将在您的案例中执行一个复制检查.这个特殊的优化叫做return value optimization (RVO).你可以通过具有副作用的构造函数来进行测试:
struct A { A(int){ std::cout << "ctor"; } A(const A & other) { std::cout << "copy ctor"; } A(A&&other) { std::cout << "move ctor"; } };