<分区>
为什么在评估完整表达式后不调用临时对象的析构函数:
#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.
}
输出:
A()
side effect
~A()
但是 12.2/3 [class.temporary] 说:
When an implementation introduces a temporary object of a class that has a non-trivial constructor (12.1, 12.8), it shall ensure that a constructor is called for the temporary object. Similarly, the destructor shall be called for a temporary with a non-trivial destructor (12.4). Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created.