#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/