gpt4 book ai didi

c++ - 在 C++ 中调用析构函数不会手动销毁对象

转载 作者:行者123 更新时间:2023-11-28 04:38:03 32 4
gpt4 key购买 nike

<分区>

我想在 C++ 中显式调用对象的析构函数来销毁该对象。

这只是一个简单的程序,用于试验编程语言的特性。我有一个将内部数据成员设置为 1 的默认构造函数,一个将内部数据成员设置为参数的重载构造函数,以及一个显示刚刚销毁对象的内部数据成员的析构函数。还有一个打印内部数据成员的函数。

#include <iostream>
using std::cout;
using std::endl;

class myClass {
public:
myClass()
{
i = 1;
cout << "default ";
cout << "constructor called with " << this->i << endl;
}

myClass(int i)
{
this->i = i;
cout << "constructor called with " << this->i << endl;
}

~myClass()
{
cout << "object " << i << " destroyed!" << endl;
}

void printData()
{
cout << "object's data is " << i << endl;
}
private:
int i; // private data member
};

int main() {
myClass a;
myClass b;
myClass c(8);

a.printData();
b.printData();
c.printData();

/* I want to explicitly destroy object b. */
b.~myClass();
b.printData();

/* all the destructors get called when the objects go out of scope */

return 0;
}

我的推理是这样的:我认为析构函数导致对象被销毁,所以它不再存在于内存中。在我显式调用析构函数后,我应该不能再使用该对象,因为它已被销毁。但是,我能够调用对象的函数并打印内部数据成员的值。手动调用析构函数是否未能销毁对象?这里发生了什么?输出:

default constructor called with 1
default constructor called with 1
constructor called with 8
object's data is 1
object's data is 1
object's data is 8
object 1 destroyed!
object's data is 1
object 8 destroyed!
object 1 destroyed!
object 1 destroyed!

调用析构函数是销毁对象,还是调用析构函数是销毁对象的结果?

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