How I implemented:
#pragma once class Singletone { private: Singletone(): instance(nullptr) {} Singletone(const Singletone&); const Singletone& operator=(const Singletone&); static Singletone * instance; ~Singletone() { delete instance; } public: static const Singletone& getInstance(); }
singletone.cpp:
#include "Singletone.h" Singletone* Singletone::instance = nullptr; const Singletone& Singletone::getInstance() { if(instance==nullptr) instance = new Singletone(); return *instance; }
Tell me, how correct is this implementation?
For example, I can not return the link because copy constructor is forbidden (which should be forbidden, right?)
What then to do, return the pointer to the object, or? ...
And what is the best way to create single-threaded singleton in C ++?
delete instance
line will cause the~Singletone()
destructor, which again executes thedelete instance
line, which again will call the destructor, and so on. Or am I missing something? - nnesterov~Singletone()
destructor will never be called at all, since the static member of the class is araw
pointer. Therefore, what you are saying will not happen, but the destructor is obviously meaningless. Sorry for misleading the previous comment:)
- Costantino Rupert