Home > Backend Development > C++ > Is the Destruction Order of Temporary Objects Guaranteed in C ?

Is the Destruction Order of Temporary Objects Guaranteed in C ?

Susan Sarandon
Release: 2024-11-12 07:49:01
Original
949 people have browsed it

Is the Destruction Order of Temporary Objects Guaranteed in C  ?

Destruction of Temporary Objects in C

Considering the following code:

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

It's evident that the output will be "one", "two", and "three." This raises the question: is this behavior guaranteed across all C compilers?

According to the C standard, in [class.temporary], it states:

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

This rule implies that temporary objects, such as the unnamed Foo object in the provided code, will be destroyed at the end of the full expression in which they were created, i.e., the semicolon at the end of the line.

It's important to note that there are exceptions to this general rule, outlined in [class.temporary] p5, p6, and p7:

  1. Shortening the lifetime of default-constructed temporary objects in array initializers.
  2. Shortening the lifetime of default arguments to constructors during array copying.
  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."

However, in the provided code, none of these exceptions apply, ensuring the guaranteed destruction of temporary objects at the end of their respective expressions.

The above is the detailed content of Is the Destruction Order of Temporary Objects Guaranteed in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template