在这种情况下use_count的价值是多少?

时间:2013-12-06 02:57:59

标签: c++ memory-leaks shared-ptr smart-pointers

我有一个这样的课:

class NotificationManager
{
public:
    static NotificationManager* Instance()
    {
        try
        {
            static std::shared_ptr<NotificationManager> instance( new NotificationManager );
            return instance.get();
        }
        catch( std::bad_alloc& )
        {
            return NULL;
        }
    }

    void foo()
    {
        //do sth
    }
}

如果我使用这个foo函数:

NotificationManager::Instance()->foo();

use_count的价值是什么?

这是一个好方法吗?如果不是什么问题?

1 个答案:

答案 0 :(得分:0)

instance.use_count()等于1。

为什么不使用更传统的实现单例的方法?

class NotificationManager
{
public:
    static NotificationManager& Instance()
    {
        static NotificationManager instance;
        return instance;
    }

    void foo()
    {
        //do sth
    }
}
相关问题