gpt4 book ai didi

c++ - 在 C++ 中显式调用构造函数和析构函数

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

我知道不应该为本地成员显式调用析构函数,因为它会导致未定义的行为。但我仍然想了解以下代码的输出:

#include <iostream>
using namespace std;

class Test
{
public:
Test() { cout << "Constructor is executed\n"; }
~Test() { cout << "Destructor is executed\n"; }
friend void fun(Test t);
};
void fun(Test t)
{
Test(); //3.calls constructor and destructor
t.~Test(); //4. calls destructor
}
int main()
{
Test(); // 1. calls constructor and destructor
Test t; // 2.calls constructor
fun(t);
return 0; //5. compiler calls destructor for t
}

预期输出(最后调用 3 个析构函数):

Constructor is executed
Destructor is executed
Constructor is executed
Constructor is executed
Destructor is executed
Destructor is executed
Destructor is executed

实际输出(最后调用了 4 次析构函数):

Constructor is executed
Destructor is executed
Constructor is executed
Constructor is executed
Destructor is executed
Destructor is executed
Destructor is executed
Destructor is executed

最后额外的析构函数调用在哪里?

最佳答案

您按值将 t 传递给 fun。它创建一个拷贝。你看不到的原因是你没有让复制构造函数打印任何东西。但你确实看到它被破坏了。

关于c++ - 在 C++ 中显式调用构造函数和析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38205941/

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