c++ - 为什么这个 C++11 中的 Singleton 不能正常工作?

标签 c++ c++11 singleton

#include <memory>
#include <mutex>

template<typename T>
class Singleton
{
    public:
    Singleton() = default;
    ~Singleton() = default;
    //forbid copy and asign
    Singleton(const Singleton &) = delete;
    Singleton&operator=(const Singleton&) = delete;

    //make singleton instance by args
    template <typename...Args>
    static void makeInstance(Args&&...args)
    {
        std::call_once(flag, make_shared_instance<T>, std::forward<Args>(args)...);
    }

    //get instance
    static std::shared_ptr<T> Instance()
    {
        if (!instance)
        {
            throw std::exception("instance not make!");
        }

        return instance;
    }

private:
    template <typename...Args>
    static void make_shared_instance(Args&&...args)
    {
        instance = std::make_shared<T>(std::forward<Args>(args)...);
    }

    static std::once_flag flag;
    static std::shared_ptr<T> instance;
};

int main()
{
    Singleton<double>::makeInstance(10);   // OK
    Singleton<int>::makeInstance();        // compilation error
}

当我像这样使用参数时

Singleton<double>::makeInstance(10); 

它运行良好但没有参数

Singleton<int>::makeInstance();

这是行不通的。这是为什么?

最佳答案

您的 makeInstance 有误功能;你是专业的 make_shared_instance使用错误的模板参数。正确的代码是

std::call_once(flag, make_shared_instance<Args...>, std::forward<Args>(args)...);
//                                       ^^^^^^^^

您的代码 Singleton<double>::makeInstance(10);有效是因为 int 类型的参数可转换为 double .但是当你称它为 Singleton<int>::makeInstance(); 时, make_shared_instance<int>需要一个参数,而你还没有提供任何参数。


此外, std::exception 没有采用字符串文字参数的构造函数。您可能正在使用 VC++,它有一个允许您的代码编译的非标准构造函数。你应该抛出 std::runtime_error 相反。

关于c++ - 为什么这个 C++11 中的 Singleton 不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33991196/

相关文章:

singleton - 如何使用 AFHTTPRequestOperation 更新 MBProgressHud

ios - 创建 ViewController 的单例对象

scala - 将单例对象编码为惰性值

c++ - 将货币格式字符串转换为 double

C++ 错误 C3646、C2059 和 C2238 Visual Studio 2015(社区)

c++ - 在执行期间重新分配 std::function 对象

c++ - std::thread 通过引用传递调用复制构造函数

c++ - 错误: no match for call to (std::string{aka std::basic_string<char>})(const char[5])'

c++ - Qt - 遍历 QRadioButtons

c++ - 我可以在非 void 返回函数上使用 [[noreturn]] 吗?