单例类,智能指针和析构函数被调用

时间:2017-11-29 17:19:53

标签: c++ c++11

我想创建一个单例类,当所有指向该类的指针都消失时,会调用析构函数。

#include <memory>
#include <iostream>

class MyClass {
public:
    uint8_t str[50]; //some random data
    MyClass() {LOG("constructor Called"); }
    ~MyClass() {LOG("destructor Called");}
    static std::shared_ptr<MyClass> &Get();

private:
    static std::shared_ptr<MyClass> instance;
};

std::shared_ptr<MyClass> MyClass::instance=NULL;


std::shared_ptr<MyClass> &MyClass::Get()
{
    if (instance == NULL)
    {
        instance= std::shared_ptr<MyClass>(new MyClass());
        return instance;
    }
    return instance;
}

int main()
{
    std::shared_ptr<MyClass> &p1 =MyClass::Get();

    printf("We have %" PRIu32, p1.use_count());
    if (1)
    {
        std::shared_ptr<MyClass> &p2 =MyClass::Get();//this should not  
                                                     //  create a new class
        printf("We have %" PRIu32, p1.use_count());  //this should be two...
        printf("We have %" PRIu32, p2.use_count());  //this should be two...
        //when p1 goes out of scope here it should not call destructor
    }
    printf("We have %" PRIu32, p1.use_count());

    //now destructor should be called
    return 0;
}

上面的代码不起作用,因为静态实例是一个智能指针,永远不会超出范围,因此永远不会调用析构函数。

我想要做的是首次创建静态实例以返回智能指针的这个实例,然后在返回此智能指针的副本之后每次调用。

1 个答案:

答案 0 :(得分:2)

std :: weak_ptr是您正在寻找的。

通过将实例更改为weak_ptr,它不会被视为共享指针的所有者;意味着一旦释放了所有其他引用,对象就会被销毁。也就是说,它确实让你的&#34; Get&#34;函数稍微复杂一点,你必须尝试从弱ptr获取shared_ptr,然后在成功返回它时,或者在失败时创建一个新的,重新分配实例到该ptr并返回。

您可以找到更多here

作为单独的注释,将调用静态成员的析构函数,而不是在main返回之前。大多数人都接受静态的这个特性,因为一旦主要回归,他们就不会真正关心只要应用程序没有崩溃就会发生什么事情(尽管使用其他静态的静力学往往会导致这种情况发生)

相关问题