返回临时对象是否在C中创建一个临时对象?

考虑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";
    }
};

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...