Alexandrescu singleton with policies - c++

I was looking into Alexandrescu's singleton created with policies, which is an interesting design. (http://loki-lib.sourceforge.net/html/a00670.html)
However, he first explains that you should guarantee a Singleton's uniqueness, which I agree with. But when you look at the policy implementation, he has a policy CreateWithNew which invokes the new operator on the argument provided with T. which means the constructor has to be public, meaning any user creating the singletonHolder can also instantiate that class directly himself.
Obviously it is still a nice design, but I just wanted to make sure if I missed something important or if he sacrificed the uniqueness for a versatile design.
Thanks!
A test example:
The following class has a TestObject which is the Singleton class, and a simple createViaNewPolicy which just uses new to allocate the singleton. notice that the constructor of TestObject has to be public in order for this to work.
//////////////////////////////////////////////////////////////////////////
class TestObject
{
public: // change this to private (to guarantee uniqueness) but then it wont compile
TestObject() {}
int foo() {return 1;}
~TestObject() {}
};
//////////////////////////////////////////////////////////////////////////
template< class T, template <class> class CreationPolicy >
class SingletonHolder
{
public:
T* SingletonHolder<T, CreationPolicy>::Instance()
{
if (!pInstance_)
{
pInstance_ = CreationPolicy<T>::Create();
}
return pInstance_;
}
private:
static T* pInstance_;
};
template< class T, template <class> class CreationPolicy >
T* SingletonHolder<T, CreationPolicy>::pInstance_;
//////////////////////////////////////////////////////////////////////////
template<class T>
class CreateViaNew
{
public:
static T* Create()
{
return new T();
};
};
//////////////////////////////////////////////////////////////////////////
int _tmain(int argc, _TCHAR* argv[])
{
SingletonHolder<TestObject, CreateViaNew> mySingletonHolder;
TestObject* testObj = mySingletonHolder.Instance();
return 0;
}

CreateUsingNew is just the policy. They way it's used is as a template template parameter inside the Singleton class. So the singleton class will have the following layout (exctract from modern C++ design) :
class Singleton
{
Singleton& Instance();
... operations...
public:
Singleton();
Singleton(Singleton const&);
Singleton& operator=(Singleton const&);
~Singleton();
}
There the creation of the object can only be done through the Instance method. In turn that method reads (extract from the link to Loki) :
template
<
class T,
template <class> class CreationPolicy,
... some other arguments...
>
void SingletonHolder<T, CreationPolicy,
...some other arguments...>::MakeInstance()
{
... stuff ...
if (!pInstance_)
{
if (destroyed_)
{ /* more stuff */ }
pInstance_ = CreationPolicy<T>::Create();
/* even more stuff */
}
}
So the line where the magic happens is pInstance = CreationPolicy<T>::Create();
Itself, every construction method for a Singleton object is private and underlying implementation of the construction policy can only be accessed through the public MakeInstance method

Related

Implementing a ReaderWriter class based upon separate stateful Reader and Writer bases

Suppose I have two classes...
We can call the first FooReader and it looks something like this:
class FooReader {
public:
FooReader(const Foo* const foo)
: m_foo(foo) {
}
FooData readFooDataAndAdvance() {
// the point here is that the algorithm is stateful
// and relies upon the m_offset member
return m_foo[m_offset++];
}
private:
const Foo* const m_foo;
size_t m_offset = 0; // used in readFooDataAndAdvance
};
We can call the second FooWriter and it looks something like this:
class FooWriter {
public:
FooWriter(Foo* const foo)
: m_foo(foo) {
}
void writeFooDataAndAdvance(const FooData& foodata) {
// the point here is that the algorithm is stateful
// and relies upon the m_offset member
m_foo[m_offset++] = foodata;
}
private:
Foo* const m_foo;
size_t m_offset = 0;
};
These both work wonderfully and do their job as intended. Now suppose I want to create a FooReaderWriter class. Note that the
I naturally want to say that this new class "is a" FooReader and "is a" FooWriter; the interface is simply the amalgamation of the two classes and the semantics remain the same. I don't want to reimplement perfectly good member functions.
One could model this relationship using inheritance like so:
class FooReaderWriter : public FooReader, public FooWriter { };
This is nice because I get the shared interface, I get the implementation and I nicely model the relationship between the classes. However there are problems:
The Foo* member is duplicated in the base classes. This is a waste of memory.
The m_offset member is separate for each base type, but they need to share it (i.e. calling either readFooDataAndAdvance and writeFooDataAndAdvance should advance the same m_offset member).
I can't use the PIMPL pattern and store m_foo and m_offset in there, because I'd lose the const-ness of the m_foo pointer in the base FooReader class.
Is there anything else I can do to resolve these issues, without reimplementing the functionality contained within those classes?
This seems ready made for the mixin pattern. We have our most base class which just declares the members:
template <class T>
class members {
public:
members(T* f) : m_foo(f) { }
protected:
T* const m_foo;
size_t m_offset = 0;
};
and then we write some wrappers around it to add reading:
template <class T>
struct reader : T {
using T::T;
Foo readAndAdvance() {
return this->m_foo[this->m_offset++];
};
};
and writing:
template <class T>
struct writer : T {
using T::T;
void writeAndAdvance(Foo const& f) {
this->m_foo[this->m_offset++] = f;
}
};
and then you just use those as appropriate:
using FooReader = reader<members<Foo const>>;
using FooWriter = writer<members<Foo>>;
using FooReaderWriter = writer<reader<members<Foo>>>;
CRTP.
template<class Storage>
class FooReaderImpl {
public:
FooData readFooDataAndAdvance() {
// the point here is that the algorithm is stateful
// and relies upon the m_offset member
return get_storage()->m_foo[get_storage()->m_offset++];
}
private:
Storage const* get_storage() const { return static_cast<Storage const*>(this); }
Storage * get_storage() { return static_cast<Storage*>(this); }
};
template<class Storage>
class FooWriterImpl {
public:
void writeFooDataAndAdvance(const FooData& foodata) {
// the point here is that the algorithm is stateful
// and relies upon the m_offset member
get_storage()->m_foo[get_storage()->m_offset++] = foodata;
}
private:
Storage const* get_storage() const { return static_cast<Storage const*>(this); }
Storage * get_storage() { return static_cast<Storage*>(this); }
};
template<class T>
struct storage_with_offset {
T* m_foo = nullptr;
std::size_t m_offset = 0;
};
struct FooReader:
FooReaderImpl<FooReader>,
storage_with_offset<const Foo>
{
FooReader(Foo const* p):
storage_with_offset<const Foo>{p}
{}
};
struct FooWriter:
FooWriterImpl<FooWriter>,
storage_with_offset<Foo>
{
FooWriter(Foo* p):
storage_with_offset<Foo>{p}
{}
};
struct FooReaderWriter:
FooWriterImpl<FooReaderWriter>,
FooReaderImpl<FooReaderWriter>,
storage_with_offset<Foo>
{
FooReaderWriter(Foo const* p):
storage_with_offset<Foo>{p}
{}
};
If you need an abstract interface for runtime polymorphism, inherit FooReaderImpl and FooWriterImpl from them.
Now, FooReaderWriter obeys the ducktype contract of FooReader and FooWriter. So if you use type erasure instead of inheritance, it will qualify for either (at point of use).
I'd be tempted to change them to
using FooReader = std::function<FooData()>;
using FooWriter = std::function<void(FooData const&)>;
and then implement a multi-signature std::function for FooReaderWriter. But I'm strange and a bit unhinged that way.

Is this a correct Implemenation of the Singleton Pattern? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
The following code is my implementation of the Singleton Pattern.
#include <iostream>
template<class T>
class Uncopyable
{
protected:
Uncopyable(){}
~Uncopyable(){}
private:
Uncopyable(const Uncopyable<T>&);
Uncopyable& operator=(const Uncopyable<T>&);
};
template <class T>
class Singleton : private Uncopyable<T>
{
public:
static T* getInstancePtr()
{
return instance;
}
protected:
Singleton<T>()
{
if(instance == 0)
{
instance = new T();
}
};
~Singleton<T>()
{
};
private:
static T* instance;
};
template<class T> T* Singleton<T>::instance = 0;
class Test : public Singleton<Test>
{
public:
Test(){};
~Test(){};
inline void test() const
{
std::cout << "Blah" << std::endl;
}
private:
friend class Singleton<Test>;
protected:
};
int main(int argc, char* argv[])
{
Test* t = Test::getInstancePtr();
Test* t2 = Test::getInstancePtr();
t->test();
t2->test();
return 0;
}
It works in this form, however I am uncertain as to whether it really is correct due to the constructor and destructor of the Singleton being protected as opposed to being private. If I declare them as private the code will not compile as they are not accessible to the class. Is this implementation safe to use, or is there anything I can do to improve it to ensure only one instance will be created and used.
Thanks
That is most certainly an incorrect implementation of singleton. There are too many issues with that implementation.
In C++11, you can make use of std::call_once and std::once_flag to implement singleton pattern. Here is one example:
//CRTP base singleton class
template<typename TDerived>
class Singleton
{
static std::unique_ptr<TDerived> m_instance;
static std::once_flag m_once;
protected:
Singleton() {}
public:
~Singleton() { }
static TDerived & GetInstance()
{
std::call_once
(
Singleton::m_once,
[] (){ Singleton::m_instance.reset( new TDerived() ); }
);
return *m_instance;
}
};
template<typename TDerived>
std::unique_ptr<TDerived> Singleton<TDerived>::m_instance;
template<typename TDerived>
std::once_flag Singleton<TDerived>::m_once;
Now you can derive from it as:
class Demo : public Singleton<Demo>
{
public:
void HelloWorld() { std::cout << "HelloWorld" << std::endl; }
};
//call HelloWorld() function through singleton instance!
DemoSingleton::GetInstance().HelloWorld();
There are several things wrong with the code you've posted.
The Uncopyable class doesn't need to be templated
The Singleton class isn't thread safe
Your Singleton instance is never deleted
I would re-implement your accessor as:
static T& GetInstance()
{
static T instance;
return instance;
}
Then make sure you call Singleton<T>::GetInstance() in the main thread of your application (during initialisation) to avoid any threading issues.
your destructor private will cause the compile error?cause when the process ends,the compile cannot call the private function so the object cannot be delete
No this is not a good implementation of the singleton pattern, it does not work!
The only instance of Test in the example is NULL! The constructor is never called!
You need to change Singleton::getInstancePtr to:
public:
static T* getInstancePtr()
{
if(instance == 0)
{
instance = new T();
}
return instance;
}
protected:
Singleton<T>() {};
The constructor for Test will now be called.
Usually singleton objects live for the lifetime of the program, so I do not implement them like that, because you use dynamic allocation, then someone must free it and you return a pointer to your singleton object, then you may accidentally delete it, so I will use something like this:
template< class T >
struct Singleton : Uncopyable<T> {
public:
static T& get_instance() {
static T res;
use( res ); // make sure object initialized before used
return res;
}
private:
static void use( T& ) {}
};
There is no correct implementation of the Singleton anti-pattern in C++.
The main issues with this attempt are:
The semantics are a very weird and error-prone; you must instantiate Singleton somewhere in order to create the instance. You example never creates the instance, and t->test() is erroneously calling a function via a null pointer.
Construction is not thread-safe; two instances could be created if two unsynchronised threads both instantiate Singleton.
If the instance is actually created, then it is leaked.
A less erroneous implementation might be more like this:
template <typename T>
T & singleton()
{
static T instance;
return instance;
}
but this still has issues: in particular, the instance may be destroyed before other static objects, which may attempt to access it in their destructors.

Static Singleton?

Is it possible to make a generic singleton? I want to create something I can just inherit from and get the functionality of a singleton. I'm having trouble with using templates with static members.
Shouldn't this work?
**
UPDATED
**
Thanks for the replies so far. So now my problem is that GameEngine can't see it's own constructor. I know it's private but still.
Singleton.h
template <typename T>
class Singleton
{
private:
static std::shared_ptr<T> m_Instance;
public:
static std::shared_ptr<T> Instance();
};
template<typename T>
std::shared_ptr<T> Singleton<T>::m_Instance = nullptr;
template<typename T>
std::shared_ptr<T> Singleton<T>::Instance()
{
if(m_Instance == nullptr)
m_Instance = std::make_shared<T>();
return m_Instance;
}
GameEngine.h
class GameEngine : public Singleton<GameEngine>
{
private:
GameEngine();
};
I don't see how that'd work, since there's nothing preventing you from creating more instances of GameEngine.
Even if it were possible (and it is) to have a generic way of creating a singleton (perhaps involving macros), I would advise against it, because situations where you actually want singletons are rare. Let me rephrase that... situations where you actually really need a singleton are rare.
The best way to create a singleton is as follows:
class GameEngine
{
public:
static GameEngine& instance() { static GameEngine e; return e; }
private:
GameEngine() {}
GameEngine(const GameEngine&) = delete;
};
The e variable will be (thread-safely) initialized on first call to instance, and it will be destroyed on orderly process exit. The private/deleted constructors prevent a second instance from ever being created.

Extract common class behaviour in a template

I observed that in my program I needed to make several classes use the following common pattern. The idea behind it is that resource_mgr maintains a list of reference-counted pointers to resource objects, and exclusively controls their lifetime. Clients may not create or delete resource instances, but may request them from resource_mgr.
class resource_impl
{
public:
// ...
private:
resource_impl(...);
~resource_impl();
// ...
friend class resource_mgr;
}
class resource_mgr
{
public:
// ...
shared_ptr<resource_impl> new_resource(...);
private:
std::vector<shared_ptr<resource_impl> > resources_;
static void delete_resource(resource* p); // for shared_ptr
}
How can I (or can I?) define a template to capture this common behavior?
The following illustrates how this template might be used:
class texture_data
{
// texture-specific stuff
}
typedef resource_impl<texture_data> texture_impl;
// this makes texture_impl have private *tors and friend resource_mgr<texture_impl>
typedef resource_mgr<texture_impl> texture_mgr;
//...
texture_mgr tmgr;
shared_ptr<texture_impl> texture = tmgr.new_resource(...);
Update: Various instantiations of resource_impl should all have in common the following properties:
They have private constructors and destructor
Their "associated" resource_mgr (the manager class that manages the same type of resource) is a friend class (so it can create/destroy instances)
First add the interface :
class resource_interface
{
public:
virtual ~resource_interface() = 0;
virtual void foo() = 0;
};
Then change the resource_impl into template :
template< typename T >
class resource_impl : public T
{
public:
// ...
private:
resource_impl(...);
~resource_impl();
// ...
friend template< typename > class resource_mgr;
}
Then change resource_mgr into template:
template< typename T >
class resource_mgr
{
public:
// ...
shared_ptr<T> new_resource(...);
private:
std::vector<shared_ptr<T> > resources_;
static void delete_resource(T* p); // for shared_ptr
}
And you should have very generic resource_impl and resource_mgr classes.

c++ template problem

i have a class which has a template by other purposes:
template<class t>
class MyClass {
public: //of course public...
t foo;
std::string text;
}
and i have another class which method get all kind of these class through the arguments, and want to store the pointer in an array. The class dont want to access the specific (tempalted) parts of the classes only the common attributes/methods.
class Container {
public: //of course public...
MyClass* array; //this is allocated with some magic.
void bar(MyClass& m) {
and want to store the class in a MyClass* array.
}
}
here is the error that argument list for template missing
how can i solve this?
The simplest method would be to make that function a template as well:
template <class t>
void bar(MyClass<t>& m) {
// ...
}
Note that that should probably be const MyClass<t>&, because you don't need to modify it.
Your new code is meaningless. There is no such that as an object of type MyClass, because MyClass is a template. If you want to operate on these classes irrespective of their template argument, then you need to factor out the non-template portions as a base class:
class MyClassBase
{
public:
// polymorphic base classes should always have virtual destructors
~MyClassBase() {}
virtual void some_function() = 0;
};
template <typename T>
class MyClass : public MyClassBase
{
public:
// implement abstract functions
void some_function()
{
// template argument T is available here
}
};
Then you can refer to that base, and when you call a virtual function it will dynamically dispatch:
class Container
{
public:
// no magic: use a std::vector for dynamic arrays
std::vector<MyClassBase*> array; // not by value! avoid slicing
void bar(MyClassBase& m)
{
array.push_back(&m);
}
void baz()
{
array[0]->some_function(); // for example
}
};
How about putting a common base class.
class MyClassCommon {
protected:
~MyClassCommon() { }
public:
std::string text;
};
template<class t>
class MyClass : public MyClassCommon {
public: // of course public...
t foo;
};
class Container {
public: // of course public...
MyClassCommon* array; // this is allocated with some magic.
void bar(MyClassCommon& m) {
/* ... */
}
};
If you want to create a "multi-template" array, you'd better use a non-template class as a base class of a template class. Or you can make a template array and store any objects in it.
the text variable in your class is private so unless you bar function is a method of the class you can't legally use it like that