假设我有以下单例基类:
template <class Derived>
class Singleton
{
public:
inline static Derived* get();
protected:
Singleton();
~Singleton();
static std::unique_ptr<Derived> _uptr;
private:
Singleton(const Singleton&);
Singleton & operator = (const Singleton&);
};
// Initialize the singleton object.
template <class Derived>
std::unique_ptr<Derived> Singleton<Derived>::_uptr = nullptr;
// Constructor
template <class Derived>
Singleton<Derived>::Singleton() {
}
// Constructor
template <class Derived>
Singleton<Derived>::~Singleton() {
}
// Function: get
template <class Derived>
inline Derived* Singleton<Derived>::get() {
if(_uptr != nullptr) return _uptr.get();
std::unique_ptr<Derived> tmp(new Derived());
_uptr = std::move(tmp);
return _uptr.get();
}我有以下派生类:
class Foo : public Singleton <Foo> {
public:
int value;
}
int main() {
Foo A;
Foo B;
A.value = 1;
B.value = 2;
A.get()->value = 3;
cout << A.value << endl; // we get 1
cout << B.value << endl; // we get 2
cout << A.get()->value() << " " << B.get()->value() << endl; // we get 3
}我想知道为什么这三种方法在value上提供了完全不同的输出。A和B不应该在继承相同的单例基时返回相同的值吗?具体来说,我希望实现一个具有全局范围的类,并且只启动一次。
发布于 2015-11-30 19:08:34
您仍然需要解释地删除派生Singleton类中的(自动创建的)默认构造函数和赋值运算符,以禁止实例化多个实例:
class Foo : public Singleton <Foo> {
public:
int value;
delete Foo();
delete Foo(const Foo&);
delete Foo& operator(const Foo&);
}发布于 2015-11-30 19:05:40
我想你误解了单身模式。
之所以称为单例,是因为只允许一个实例。这是通过将构造函数设置为私有来完成的,因此您只能通过get函数创建实例。
因此,Foo A和Foo B是非法的。
您得到了错误的值,因为您创建了3个实例--这不是单个实例。
请参阅pattern
发布于 2015-11-30 19:10:47
类Foo有一个成员变量int value,还有一个静态成员变量std::unique_ptr<Foo> _uptr。
A.value = 1; // now A.value == 1 and _uptr == nullptr
B.value = 2; // now B.value == 2 and _uptr == nullptr
A.get()->value = 3; // now _uptr points to a Foo whose value is 3有三个Foos和三个价值观。
https://stackoverflow.com/questions/34005636
复制相似问题