gpt4 book ai didi

C++ 在单例中管理堆/指针

转载 作者:行者123 更新时间:2023-11-28 05:14:54 26 4
gpt4 key购买 nike

我有一个单例,其属性是指针。

当我不再使用它时,即当对我的实例的最后一个引用从堆栈帧中弹出时,如何防止内存泄漏?

是否每次从堆栈中弹出引用时都会调用析构函数?

A &A::getInstance()
{
static A instance; // does this get deleted at any point?
return instance;
}

最佳答案

您的单例对象将在程序的整个生命周期内存在,并在 main 结束后的某个时间被销毁。那时它的析构函数将被调用。

在这里您可以删除您的原始指针(或者如果使用智能,您可以设置为nullptr 或调用reset)。

这可以在下面的例子中看到:

#include <iostream>
#include <string>
#include <memory>

class Foo
{
public:

Foo(std::string const& name = "Unknown")
: m_sName{ name }
{
std::cout << m_sName << " is created" << std::endl;
}

~Foo()
{
std::cout << m_sName << " is being destroyed" << std::endl;
}

std::string m_sName;
};

class Singleton
{
public:

static Singleton& Get()
{
static Singleton instance;
return instance;
}

~Singleton()
{
delete m_RawFoo;
m_SmartFoo = nullptr;
}

void print() const
{
std::cout << "Hello World" << std::endl;
}

protected:

private:

Singleton()
{
m_RawFoo = new Foo{ "Raw Foo" };
m_SmartFoo = std::make_shared<Foo>("Shared Foo");
}

Foo* m_RawFoo;
std::shared_ptr<Foo> m_SmartFoo;
};

int main()
{
std::cout << "Starting main..." << std::endl;

Singleton::Get().print();
Singleton::Get().print();

std::cout << "Ending main..." << std::endl;

return 0;
}

输出如下:

Starting main...
Raw Foo is created
Shared Foo is created
Hello World
Hello World
Ending main...
Raw Foo is being destroyed
Shared Foo is being destroyed

关于C++ 在单例中管理堆/指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42865674/

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