我发现了这个单例的实现。我怎样才能创建指向它的指针或共享指针?`
为什么这不起作用?自动测试 = Singleton::Instance();
class Singleton
{
công cộng:
static Singleton & Instance()
{
static Singleton myInstance;
return myInstance;
}
// delete copy and move constructors and assign operators
Singleton(Singleton const&) = delete; // Copy construct
Singleton(Singleton&&) = delete; // Move construct
Singleton& operator=(Singleton const&) = delete; // Copy assign
Singleton& operator=(Singleton &&) = delete; // Move assign
// Any other public methods
được bảo vệ:
Singleton()
{
}
~Singleton()
{
}
// And any other protected methods.
};
And why is this not working? auto test = Singleton::Instance();
如果您查看编译错误,它会告诉您。
main.cpp:31:37: error: use of deleted function 'Singleton::Singleton(const Singleton&)'
您正在尝试复制对象。但是复制构造函数被删除,因此该类型不可复制。
您可能打算引用而不是复制:
auto& test = Singleton::Instance();
How can I make a pointer ... to this?
您可以通过使用地址运算符获取它的地址来分配指向单例的指针:
auto* test = &Singleton::Instance();
or a shared pointer
您不能拥有指向具有静态存储的对象的共享指针 - 除非您使用特殊的删除器,但这样的共享指针几乎没有用处。由于您的单例具有静态存储,因此您不想使用共享指针。您可以修改单例以将静态存储的共享指针保留为动态分配的对象。然后你可以有一个共享指针。
Tôi là một lập trình viên xuất sắc, rất giỏi!