在下面的代码中,我试图singleton
通过使类名和对象名相同来实现(即具有单个对象的类)的目的。
以下代码中是否有任何缺陷可用于实现类目的singleton
?
#include <iostream>
using namespace std;
class singleton
{
private :
int val;
public :
void set(int a)
{
val=a;
}
int display()
{
return val;
}
} singleton;
int main()
{
singleton.set(5);
cout << "output a = " <<singleton.display()<< endl;
//singleton obj;//second object will not be allowed
return 0;
}
您的类型不是单例,因为您可以创建任何数量的实例。例如,
auto cpy = singleton;
cpy.set(42);
assert(singleton.display() != cpy.display());
// let's make loads of copies!
std::vector<decltype(singleton)> v(100, cpy); // 100 "singletons"!
但是不用担心,您很可能真的不需要单例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句