Search code examples
c++returntype-conversiontemporary-objects

Does returning a temporary object create a temporary object in C++?


Consider the following code in C++:

struct A {A(int);};
A foo() {return static_cast<A>(0);}
A x = foo();

Here static_cast<A>(0) creates a temporary object by the standard [5.2.9-4], which is a prvalue. The standard [12.2-1] says

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

So does the return statement will creates a temporary object again?

By the way, can anyone please tell me whether the standard guarantees an implicit type conversion will create an temporary object?


Solution

  • (§4/6) mentions that

    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.

    So yes, unless optimized, a temporary should be created, but I'm sure all modern compilers will perform a copy elision in your case. This particular optimization is called return value optimization (RVO). You can easilly test it by having constructors with side effects:

    struct A {
        A(int){
            std::cout << "ctor";
        }
        A(const A & other)
        {
            std::cout << "copy ctor";
        }
        A(A&&other)
        {
            std::cout << "move ctor";
        }
    };