【问题标题】:what's the value of use_count in this situation?在这种情况下 use_count 的值是多少?
【发布时间】:2013-12-23 06:49:37
【问题描述】:

我有一个像 thsi 这样的课程:

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 的值是多少?

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

【问题讨论】:

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


    【解决方案1】:

    instance.use_count() 将等于 1。

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

    class NotificationManager
    {
    public:
        static NotificationManager& Instance()
        {
            static NotificationManager instance;
            return instance;
        }
    
        void foo()
        {
            //do sth
        }
    }
    

    【讨论】:

    • 无论如何,这不是线程安全的单例,除非您使用 C++11 标准。 (如果多个线程在调用 Instance() 之前同时访问 Instance(),那么它们可以接收不同的存储空间。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多