Home >Backend Development >C++ >When Do Temporary Objects in C Get Destroyed?

When Do Temporary Objects in C Get Destroyed?

Susan Sarandon
Susan SarandonOriginal
2024-11-26 09:27:10354browse

When Do Temporary Objects in C   Get Destroyed?

Temporary Object Destruction in C

When do temporary objects in C get destroyed? This question arises when considering the following code snippet:

#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';
}

The code prints "one," "two," and "three." This behavior might seem unexpected if temporary objects were destroyed immediately after their creation. However, that is not the case.

Temporary objects, as defined in [class.temporary] p4, are destroyed at the end of the full expression containing the point where they were created. In the example above, the full expression is the entire main function, so the temporary Foo objects are destroyed at the semicolon.

This behavior is standard-guaranteed, making the output of the given code consistent across C compilers. However, there are some exceptions to the general rule:

  • Default-constructed temporary objects in array initializers can have their lifetime shortened.
  • Default arguments to constructors during array copying can also have their lifetime shortened.
  • Binding a reference to temporary objects extends their lifetime.
  • Temporary objects in a for-range-initializer have an extended lifetime.

The above is the detailed content of When Do Temporary Objects in C Get Destroyed?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn