gpt4 book ai didi

c++ - 为什么对象 'destructed' 两次?

转载 作者:太空狗 更新时间:2023-10-29 23:39:59 42 4
gpt4 key购买 nike

<分区>

在下面的代码中,a 的析构函数被调用了两次,第一次调用似乎被忽略了:

struct A1
{
int A;
A1(int a=0) : A(a) { std::cout << "ctor: " << A << "\n"; std::cout.flush(); }
~A1() { std::cout << "dtor: " << A << "\n"; std::cout.flush(); }
};


int main()
{
A1 a(1), *pa=new A1(2), *pb=new A1(3);

a.~A1();
pa->~A1();
delete pb;
std::cout << "'destructed' a.A = " << a.A << "\n"; std::cout.flush();

return 0;
}

输出:

ctor: 1
ctor: 2
ctor: 3
dtor: 1
dtor: 2
dtor: 3
'destructed' a.A = 1
dtor: 1

这里发生了什么?

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