gpt4 book ai didi

c++ - 单例:为什么不需要删除并且看不到析构函数调试消息

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:31 25 4
gpt4 key购买 nike

我的导师说我们不需要删除在堆中创建的单例对象,因为当超出范围时,它的内存会被释放并自动删除。

是不是编译器以不同的方式对待静态对象,我们不需要担心从堆中删除这个对象?

在下面的代码中,我认为是指针超出了 main 的范围,而不是堆本身中的对象,但在某些时候,如果确实为此对象释放了内存,则应该调用对象的析构函数?

我也尝试在 main 中添加成员函数 DeleteObject,但我看不到正在调用堆中对象的析构函数。

但仍然看不到析构函数在屏幕上显示消息。

#include <iostream>
using namespace std;

class Singleton {
public:
static Singleton* GetInstance();
void Show() { cout << "Single object"; }
void DeleteObject();
~Singleton();

private:
static Singleton* psingleton;
Singleton();
};

void Singleton::DeleteObject() {
delete psingleton;
}

Singleton::~Singleton() {
cout << "\n\nAt Destructor";
}

Singleton* Singleton::psingleton = 0;
Singleton::Singleton()
{
//do stuff
}

Singleton* Singleton::GetInstance() {
if (psingleton = NULL ) {
psingleton = new Singleton();
}
return psingleton;
}

int main()
{
Singleton::GetInstance()->Show();
Singleton::GetInstance()->DeleteObject();//another try
return 0;
}

期望对象析构函数在屏幕上显示一条消息,因为它被调用了。

最佳答案

那是因为你有一个错误。这里是

Singleton* Singleton::GetInstance() {
if (psingleton = NULL) {
psingleton = new Singleton();
}
return psingleton;
}

永远不会创建对象,因为 psingleton = NULL 总是转换为 false。你想要的是 if (psingleton == NULL) {

通过该修复,我在 MSVC 中的输出是:

Single object

At Destructor

... 这是因为调用了 Singleton::GetInstance()->DeleteObject();,而不是因为程序已经结束。


I think it's the pointer that goes out of scope in main and not the object in the heap itself, but at some point the destructor of the object should be called if indeed the memory is released for this object?

你是对的。堆上的对象不会超出范围,并且不会从程序结束时调用析构函数。

关于c++ - 单例:为什么不需要删除并且看不到析构函数调试消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54588265/

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