Home >Backend Development >C++ >Why Are Temporary Objects Destroyed in a Surprising Order in C ?

Why Are Temporary Objects Destroyed in a Surprising Order in C ?

DDD
DDDOriginal
2024-11-13 08:54:02338browse

Why Are Temporary Objects Destroyed in a Surprising Order in C  ?

Temporary Object Destruction in C

The provided code demonstrates a surprising behavior where temporary objects are destroyed in an unexpected order. However, this behavior is actually guaranteed by the C standard.

Explanation

Temporary objects, which are also known as unnamed objects, are created when an expression evaluates to a class type that is not a reference type. They are typically used to hold intermediate results during an expression's evaluation.

In the given code, a temporary object of type Foo is created from a character string literal, and its destructor is invoked when the object's lifetime ends. The destructor prints the name stored in the object's m_name member.

The lifetime of a temporary object ends at the end of the full expression it was created in. In the provided code, the full expression is the statement:

Foo{ "one" };

Therefore, the temporary object's lifetime ends at the semicolon following this statement. As a result, the destructor of the temporary object is invoked, and the string "one" is printed.

Exceptions to the Rule

While the general rule dictates that temporary objects are destroyed at the end of the full expression, there are a few exceptions specified in the C standard ([class.temporary] p5-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.

These exceptions allow for more flexibility in managing the lifetime of temporary objects in specific situations.

The above is the detailed content of Why Are Temporary Objects Destroyed in a Surprising Order in C ?. 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