2016-01-21 108 views
0

我发现这个实施一个Singleton的。 我怎样才能让指针或共享的指针呢?`(共享)指针Singelton

而且这是为什么不工作? 自动测试=辛格尔顿::实例();

​​
+1

为什么在这种情况下你需要共享指针?这听起来是你正试图解决一个XY问题。测试代码可以使用引用来修复:'auto&test = Singleton :: Instance();'。 –

回答

1

而且这是为什么不工作? auto test = Singleton :: Instance();

如果你看看编译错误,它会告诉你。

main.cpp:31:37: error: use of deleted function 'Singleton::Singleton(const Singleton&)' 

您试图复制对象。但复制构造函数被删除,因此该类型不可复制。

你可能是为了做一个参考,而不是一个副本:

auto& test = Singleton::Instance(); 

我怎样才能让一个指针......这样做呢?

你可以把它的地址与运营商的地址的分配指针单:

auto* test = &Singleton::Instance(); 

或共享的指针

你不能有共同的指针有静态存储的对象 - 除非你使用特殊的删除器,但这样的共享指针几乎没有用处。由于你的单例有静态存储,所以你不想使用共享指针。您可以修改您的单例以将静态存储的共享指针保留为动态分配的对象。然后你可以有一个共享指针。

+0

中声明的私有成员,您将要给shared_ptr一个空删除器 –

+0

啊 - 完美。合理。 非常感谢:) 这是一个单身人士的好方法吗? – Waterplant

+0

用这种方法不可能手动删除对象 - 对吗?或者有什么办法? – Waterplant

0

为什么没有共享指针作为类的成员,并返回?

所以你必须

shared_ptr<Singleton> Instance() 
{ 
    if(!myInstance) 
    { 
     myInstance.reset(new Singleton()); 
    } 

    return myInstance; 
} 

private: 
    shared_ptr<Singleton> myInstance; 
+0

我试过了 - 但是我收到的消息是: “无法访问在类” – Waterplant

0

原始指针:Singleton* ptr = &Singleton::Instance();auto ptr = &Singleton::Instance();

参考:Singleton& ref = Singleton::Instance();auto& ref = Singleton::Instance();

你不应该使用共享指针(因为你没有自己的单身目的)。不是没有相应地改变单身人士班。


为什么yoour代码没有工作:auto演绎类型为值类型,并试图复制instance()结果。由于Singleton是无法复制的,因此失败。