When are temporary objects destroyed?
c++, destructor, scope, temporary-objects
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:
- shortening the lifetime of default-constructed temporary objects in initializers of arrays
- shortening the lifetime of default arguments to constructors while an array is copied
- extending the lifetime of temporary objects by binding a reference to them
- extending the lifetime of temporary objects in a for-range-initializer
Problem
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'; } ```