我有一个具有指针属性的单例。

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

每次从堆栈弹出引用时,析构函数都会被调用吗?

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

最佳答案

您的单例对象将在程序的生存期内存在,并且在main结束后的一段时间内将被销毁。届时将调用析构函数。

在这里,您可以delete您的原始指针(或者,如果使用智能指针,则可以设置为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++ - C++以单例方式管理堆/指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42865674/

10-17 00:30