Destruction of temporary objects

Why not a destructor for a temporary object called after evaluating the full expression:

#include <iostream> struct A { int a; A(); ~A(); }; A::~A() { std::cout << "~A()" << std::endl; } A::A() { std::cout << "A()" << std::endl; } int main() { A b = A(); //Constructing of temporary object and applies copy-initalization std::cout << "side effect" << std::endl; //Destructor calling. } 

Demo

Conclusion:

 A() side effect ~A() 

But 12.2 / 3 [class.temporary] says:

When an implementation introduces a temporary object of a class that has a non-trivial constructor (12.1, 12.8), it must ensure that a constructor is called for the temporary object. Similarly, a destructor must be called temporarily with a nontrivial destructor (12.4). Temporary objects are destroyed as the last step in evaluating the complete expression (1.9), which (lexically) contains where they were created.

+5
source share
1 answer

With your compiler and options it is temporarily canceled (optimized), which is allowed.

Thus, the temporary does not exist.

Thus, there are no pairs of missing constructors and destructors.


It is also worth noting that copy and move constructors are the only constructors in which the compiler is allowed to assume that the constructor has no side effects, even if it knows better.

C ++ 11 ยง12.8 / 31 :
" When certain implementation criteria are met, it is allowed to omit the copy / move construct of the class object, even if the copy / move constructor and / or destructor for the object have side effects. [& Hellip;]

+2
source

Source: https://habr.com/ru/post/1204504/


All Articles