Reputation: 21200
template <class T>
class Singleton
{
public:
static T& instance()
{
boost::call_once(init, flag);
return *t;
}
static void init()
{
t.reset(new T());
}
protected:
~Singleton() {}
Singleton() {}
private:
static boost::scoped_ptr <T> t;
static boost::once_flag flag;
};
template <class T> boost::scoped_ptr<T> Singleton<T>::t(0);
template <class T> boost::once_flag Singleton<T>::flag = BOOST_ONCE_INIT;
class TestClass : public Singleton<TestClass>
{
friend class Singleton<TestClass>;
private:
TestClass(){}
};
For the above implemenation, I have a question below:
TestClass class1 = TestClass::instance();
TestClass class2 = TestClass::instance();
I found &class1 != &class2
, is this a singleton?
Upvotes: 1
Views: 1513
Reputation: 90396
TestClass class1 = TestClass::instance();
You're making a copy of the object returned by the factory, so you get a different object each time.
To prevent this, get references to your singleton:
TestClass& class1 = TestClass::instance();
Still there is something strange because making a copy of MyClass issues compiler error (it inherit from boost::noncopyable
via Singleton
, so I'm not sure how you can compiled the code you posted.
Upvotes: 4