gpt4 book ai didi

c++ - 临时对象销毁

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:44:01 32 4
gpt4 key购买 nike

<分区>

为什么在评估完整表达式后不调用临时对象的析构函数:

#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

输出:

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.

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com