Search code examples
c++scopedestructortemporary-objects

When are temporary objects destroyed?


The following code prints one,two, three. Is that desired and true for all C++ compilers?

#include <iostream>

struct Foo
{
    const char* m_name;

    ~Foo() { std::cout << m_name << '\n'; }
};

int main()
{
    Foo foo{"three"};
    Foo{"one"};   // unnamed object
    std::cout << "two" << '\n';
}

Solution

  • A temporary variable lives until the end of the full expression it was created in. Yours ends at the semicolon.

    This is in [class.temporary] p4:

    Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created.

    Your behavior is guaranteed, however, the are exceptions to this rule listed in [class.temporary] p5, p6, and p7:

    1. shortening the lifetime of default-constructed temporary objects in initializers of arrays
    2. shortening the lifetime of default arguments to constructors while an array is copied
    3. extending the lifetime of temporary objects by binding a reference to them
    4. extending the lifetime of temporary objects in a for-range-initializer