Who is responsible for destructing the block scoped static Singleton instance? - c++

I couldn't understand how the program below compiles successfully.
class SomeClass {
public: /** Singleton **/
static SomeClass &instance() {
static SomeClass singleInstance;
return singleInstance;
};
private:
SomeClass() = default;
SomeClass(const SomeClass&) = delete;
SomeClass &operator=(const SomeClass&) = delete;
~SomeClass() {}
};
int main()
{
SomeClass::instance();
// SomeClass::instance().~SomeClass(); // Compiles if destructor was public
return 0;
}
Who is responsible for calling the destructor of the Singleton
instance?
How does the underlying mechanism access a private method?

Shortly, during the construction, the compiler saves the destructor to a list of functions that will be called at the very end of the program. In the end, the list of functions, including the destructors, are called one by one and the safe destruction occurs.
Underlying Mechanism
The core of the mechanism is the exit() and atexit(..) functions provided by the C standard library. During the compilation of the program, the compiler injects some other codes around your block-scoped static variable. A pseudo representation is as below.
static SomeClass& instance() {
static SomeClass singleInstance;
/*** COMPILER GENERATED ***/
// Guard variable generated by the compiler
static bool b_isConstructed = false;
if(!b_isConstructed)
ConstructInstance(); // Constructs the Singleton instance
b_isConstructed = true;
// Push destructor to the list of exit functions
atexit(~SomeClass());
}
/*** COMPILER GENERATED ***/
return singleInstance;
};
The point here is to call the atexit(~SomeClass()) and register the destructor to the automatic call list of the exit() function which is implicitly called when you return from the main(..). As the function pointers are used instead of directly referring to the private destructor method, the access specifier protection mechanism is skipped.

Related

is there anything wrong with this Singleton class

Under these condition i wrote the next Singleton class :
1 - i want one and only one instance of the class to be present and to be accessible from the whole game engine .
2 - the Singleton is intensively used ( thousands times per frame) so i dont want to write an extra GetInstance() function , im trying to avoid any extra function call for performance
3 - one possibility is to let the GetInstance() be inlined like this :
inline Singleton* Singleton::GetInstance()
{
static Singleton * singleton = new Singleton();
return singleton;
}
but that will cause a reference problem , on each call there will be a new reference to the singleton , to fix that wrote in c++ :
class Singleton{
private:
static Singleton* singleton;
Singleton(){}
public:
static inline Singleton* GetInstance() // now can be inlined !
{
return singleton;
}
static void Init()
{
// ofc i have to check first if this function
// is active only once
if(singleton != nullptr)
{
delete singleton;
}
singleton = new Singleton();
}
~Singleton(){} // not virtual because this class can't be inherited
};
Singleton* Singleton::singleton = nullptr;
What are the possible problems i can face with this implementation ?
Your first implementation problem is a leak of the only new you call.
And the signature that force user to check pointer validity.
Your second implementation has even more problem as you require to use a 2-step initialization, and don't forbid copy/move/assignment.
Simply use Meyers' singleton:
class Singleton{
private:
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton operator&(const Singleton&) = delete;
public:
static Singleton& GetInstance()
{
static Singleton instance;
return instance;
}
};
In addition to #Jarod42's answer, I would like to point out that you could also implement a generic singleton by making template and use it in a CRTP class:
template<typename T>
class Singleton {
protected:
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton operator&(const Singleton&) = delete;
public:
static T& instance() {
static T instance;
return instance;
}
};
Then extend it:
struct MySingleton : Singleton<MySingleton> { /* ... */ };
Instead of a singleton, consider a namespace! Here's how I would do it:
// thing.h
namespace thing {
// public interface
int doSomething();
}
// thing.cpp
namespace thing {
namespace {
// private data and functions can go right here :-)
int private_data_ = 1234;
int doSomethingInternal() {
return private_data_ * 2;
}
}
// public interface
int doSomething() {
return doSomethingInternal();
}
}
Usage is simple like this:
int x = thing::doSomething();
No need for getInstance(), no memory leaks, and you can't accidentally make multiple instances.
but that will cause a reference problem , on each call there will be a new reference to the singleton
Incorrect; instead there will be a new class instance which is not the same as a reference. You will most likely end up leaking memory.
static Singleton* singleton;
Use a unique_ptr instead of a raw pointer. Compiler optimizations will devolve it into a raw pointer anyway, but now you're clearly telling the compiler what its lifespan should be.
class Singleton{
private :
static Singleton* singleton;
The default scope of a class is private; you don't need to explicity say private scope.
Singleton(){}
There is no need to provide an empty constructor when you have no other constructors in the class.
im trying to avoid any extra function call for performance
Compiled C++ will often inline such code anyway.
inline Singleton* GetInstance() // now can be inlined !
Make it static...?
~Singleton(){} // not virtual because this class can't be inherited
If your intent is to make it not inheritable, then add a final keyword to the class declaration. You can then remove the destructor.

Singleton: is there a memory leak?

This is a simple singleton:
class Singleton
{
Singleton();
virtual ~Singleton();
Singleton * Singleton::getInstance()
{
static Singleton * instance;
if (!instance) {
instance = new Singleton();
};
return instance;
};
}
When main code calls Singleton::getInstance()->someMethod() for the first time, isn't the class instantiated twice? Will be there memory leak?
I am asking because Visual Leak Detector detects memory leak on the line with new Singleton().
When main code calls Singleton::getInstance()->someMethod() for the first time, isn't the class instantiated twice?
No. Calling a static member of Singleton does not instantiate Singleton, so the only instance of Singleton to exist here is the one you create with new. And you only create it once, because once instance points to it, you never call new again.
One problem you have here, however, is that you failed to make getInstance a static member function. I assume this is a typo/oversight since, otherwise, your program would not even compile. In fact, the declaration is ill-formed even as a non-static member. Furthermore, the constructor should be private to enforce the notion that only getInstance may instantiate the type.
Will be there memory leak?
Yes, and this is what Leak Detector is reporting. However, it's minimal: the problem is that there is nothing to delete that singleton instance right before your program shuts down.
Frankly I wouldn't worry about it. This may be one of those rare times that a leak is acceptable, mostly because more than a "leak" it's just a one-time failure to de-allocate on process shutdown.
However, if you get rid of the pointer entirely then you can avoid both problems at the same time, since one of the last things your program does will be to destroy objects of static storage duration:
#include <iostream>
class Singleton
{
public:
~Singleton() { std::cout << "destruction!\n"; }
static Singleton& getInstance()
{
static Singleton instance;
return instance;
}
void foo() { std::cout << "foo!\n"; }
private:
Singleton() { std::cout << "construction!\n"; }
};
int main()
{
Singleton::getInstance().foo();
}
// Output:
// construction!
// foo!
// destruction!
(live demo)
No need even for a pointer!
This has the added benefit that the entire function becomes inherently thread-safe, at least as of C++11.
#LightnessRacesInOrbit answer is correct and to the point. Since your question is somehow dedicated to best practices when implementing a Singleton (which you should try to avoid btw), I'll give you my take on it. You can use something called the Curiously Recurring Template Pattern to create a Singleton base class which takes as a template parameter the class you want to make a Singleton. Once you've done that correctly, creating Singletons is like a walk in the park. Just derive Foo from Singleton<Foo> and make Foo::Foo() and Foo::~Foo() private. Here is the code I use, with comments, live on Coliru:
// Singleton pattern via CRTP (curiously recurring template pattern)
// thread safe in C++11 and later
#include <iostream>
#include <type_traits>
// generic Singleton via CRTP
template <typename T>
class Singleton
{
protected:
Singleton(const Singleton&) = delete; // to prevent CASE 3
Singleton& operator=(const Singleton&) = delete; // to prevent CASE 4
Singleton() noexcept = default; // to allow creation of Singleton<Foo>
// by the derived class Foo, since otherwise the (deleted)
// copy constructor prevents the compiler from generating
// a default constructor;
// declared protected to prevent CASE 5
public:
static T& get_instance()
noexcept(std::is_nothrow_constructible<T>::value)
{
static T instance;
return instance;
}
// thread local instance
static thread_local T& get_thread_local_instance()
noexcept(std::is_nothrow_constructible<T>::value)
{
static T instance;
return instance;
}
};
// specific Singleton instance
// use const if you want a const instance returned
// make the constructor and destructor private
class Foo: public Singleton</*const*/ Foo>
{
// so Singleton<Foo> can access the constructor and destructor of Foo
friend class Singleton<Foo>;
Foo() // to prevent CASE 1
{
std::cout << "Foo::Foo() private constructor" << std::endl;
}
// OK to be private, since Singleton<Foo> is a friend and can invoke it
~Foo() // to prevent CASE 2
{
std::cout << "Foo::~Foo() private destructor" << std::endl;
}
public:
void say_hello()
{
std::cout << "\t Hello from Singleton" << std::endl;
}
};
int main()
{
Foo& sFoo = Foo::get_instance();
sFoo.say_hello();
Foo& sAnotherFoo = Foo::get_instance(); // OK, get the same instance
sAnotherFoo.say_hello();
Foo& sYetAnotherFoo = sFoo; // still OK, get the same instance
sYetAnotherFoo.say_hello();
thread_local Foo& stlFoo = Foo::get_thread_local_instance(); // thread local instance
stlFoo.say_hello();
// CASE 1: error: 'Foo::Foo()' is private
// Foo foo;
// Foo* psFoo = new Foo;
// CASE 2: error: 'Foo::~Foo()' is private
Foo* psFoo = &Foo::get_instance(); // can get pointer
psFoo->say_hello();
// delete psFoo; // cannot delete it
// CASE 3: error: use of deleted function 'Foo::Foo(const Foo&)'
// Foo foo(sFoo);
// CASE 4: error: use of deleted function 'Foo& Foo::operator=(const Foo&)'
// sFoo = sAnotherFoo;
// CASE 5: error: 'Singleton<T>::Singleton() [with T = Foo]' is protected
// Singleton<Foo> direct_sFoo;
}
new Singleton() does not have a matching delete, so yea, you are leaking a resource.
You'll get memory back when the program closes, but not all resources are returned when the program ends.
You can fix it by making instance a std::auto_ptr or std::unique_ptr. Or just don't use a pointer.

C++ singleton pattern using boost::call_once

Singletons in C++ (at least prior C++11 AFAIK) can be a nightmare. With the whole static initialisation order fiasco. But boost::call_once seems to offer a robust way to implement singletons. I've tried to come up with an easy to use idiom I'd like to share for some critical feedback, hope I haven't been completely foolish :)
// Usage:
// You can make anything with a public or protected ctor a singleton.
//
// class A
// {
// public:
// ~A();
// public:
// // Optional, shorter to type
// static A& Instance() { return Singleton<A>::Instance(); }
// void foo();
//
// protected:
// explicit A(); // Can't be private, but can be public, protected is recommended.
// };
//
// Singleton<A>::Instance().foo();
// A::Instance().foo();
//
template< class T >
class Singleton : public T // inerits from T so we can access the protected constructor.
{
public:
virtual ~Singleton() {}
public:
static T& Instance();
private:
static boost::once_flag s_onceFlag;
// We use a raw pointer to avoid dynamic initialisation. If something that
// has a constructor (eg, shared_ptr ) then the dynamically initialised ctor
// may get called after the call once function is called (if the call once function
// is statically invoked before main). Then the instance pointer will be overwritten.
// Using a zero initialised pointer avoids this problem.
static T* s_instance;
private:
static void Init();
private:
explicit Singleton() {} // Used only to allow access to the protected ctor in base.
};
template< class T >
boost::once_flag Singleton<T>::s_onceFlag = BOOST_ONCE_INIT; // zero initialised variable, no order o initialisation shananigans
template< class T >
T* Singleton<T>::s_instance = 0;
template< class T >
void Singleton<T>::Init()
{
static Singleton<T> instance; // static local variable is thread safe since this function is called once only.
s_instance = &instance;
}
template< class T >
T& Singleton<T>::Instance()
{
boost::call_once( s_onceFlag, Init );
return *s_instance;
}
To be fair, I expect that call_once is a threading specific version of something that can already been had in c++11 using just a function local static initializer:
template< class T >
T& Singleton<T>::Instance()
{
static bool const init = [] () -> bool { Init(); return true; }();
return *s_instance;
}
The initializer is guaranteed not to race (in the language specification).
Worst case behaviour is when the initializer throws: the exception will propagate out of the Instance() method but next time will try to initialize again, because the specification deems the variable to have "not been initialized" when the initializer expression throws.
If in fact you "need" a thread-aware singleton (e.g. instance per thread), then you may want the thread_local keyword, with largely the same semantics.

Possible to make a singleton struct in C++? How?

I like to experiment around as I learn more about coding. I have a program that would only require a single instance of a struct for the life of it's runtime and was wondering if it's possible to create a singleton struct. I see lot's of information on making a singleton class on the internet but nothing on making a singleton struct. Can this be done? If so, how?
Thanks in advance. Oh, and I work in C++ btw.
A class and a struct are pretty much the same thing, except for some minor details (such as default access level of their members). Thus, for example:
struct singleton
{
static singleton& get_instance()
{
static singleton instance;
return instance;
}
// The copy constructor is deleted, to prevent client code from creating new
// instances of this class by copying the instance returned by get_instance()
singleton(singleton const&) = delete;
// The move constructor is deleted, to prevent client code from moving from
// the object returned by get_instance(), which could result in other clients
// retrieving a reference to an object with unspecified state.
singleton(singleton&&) = delete;
private:
// Default-constructor is private, to prevent client code from creating new
// instances of this class. The only instance shall be retrieved through the
// get_instance() function.
singleton() { }
};
int main()
{
singleton& s = singleton::get_instance();
}
Struct and class are in C++ almost the same (the only difference is default visibility of members).
Note, that if you want to make a singleton, you have to prevent struct/class users from instantiating, so hiding ctor and copy-ctor is inevitable.
struct Singleton
{
private:
static Singleton * instance;
Singleton()
{
}
Singleton(const Singleton & source)
{
// Disabling copy-ctor
}
Singleton(Singleton && source)
{
// Disabling move-ctor
}
public:
Singleton * GetInstance()
{
if (instance == nullptr)
instance = new Singleton();
return instance;
}
}
Conceptually, a struct and a class are the same in C++, so a making singleton struct is the same as making a singleton class.
The only difference between class and struct are the default access specifiers and base class inheritance: private for class and public for struct. For example,
class Foo : public Bar
{
public:
int a;
};
is the same as
struct Foo : Bar
{
int a;
};
So, there is no fundamental difference when it comes to singletons. Just make sure to read about why singletons are considered bad.
Here's a simple implementation:
struct singleton
{
static singleton& instance()
{
static singleton instance_;
return instance_;
}
singleton(const singleton&)=delete; // no copy
singleton& operator=(const singleton&)=delete; // no assignment
private:
singleton() { .... } // constructor(s)
};
First off, struct and class only refer to the default access of members. You can do everything with a struct that you can do with a class. Now if you were referring to POD structs, things get more complicated. You can't defined a custom constructor, so there's no way to enforce only a single object creation. However, there's nothing stopping you from simply only instantiating it once.
class and struct is almost a synonyms in C++. For singleton use case they are complete synonyms.

private destructor for singleton class

Is it compulsory to have a private destructor for a singleton class.
If the singleton is implemented as a variable at global scope, it must have a public destructor. Only public members are accessible at global scope.
If it's declared as a static member or static local within its own class, then the destructor may be private. The destructor is called from within class scope, where it is accessible, when the program exits. That is one way to enforce the object being a singleton. Do you need to strongly enforce that? If so, yes. It depends what you mean by "compulsory."
class A{
private:
~A() {}
public:
static A &getGlobalA() {
static A a2; // <- or here - better technique
return a2; // this is initialized upon 1st access
}; // and destroyed on program exit
static A a; // <- constructor, destructor accessed from here
};
A A::a; // <- but "called" from here in terms of control flow
This might not be what you are looking for.. But for reference, I use it as follows:
// .h
class Foo {
public:
static Foo* getInstance();
static void destroy();
private:
Foo();
~Foo();
static Foo* myInstance;
};
// .cpp
Foo* Foo::myInstance = NULL;
Foo* Foo::getInstance(){
if (!myInstance){
myInstance = new Foo();
}
return myInstance;
}
void Foo::destroy(){
delete myInstance;
myInstance = NULL;
}
Then at the end of my program, I call destroy on the object. As Péter points out the system will reclaim the memory when your program ends, so there is no real reason. The reason I use a destroy is when Ogre complained that I hadn't released all the memory I allocated. After that I just use it as "good manner", since I like cleaning up after myself.
In my opinion, the destructor of a signleton should be private. Otherwise somewone is able to call 'delete' for your singleton instance. I know, normally nobody will do it. But if we talk about excellence design, it must be resistant to all possible intended or unitnended damages.
With the modern C++ it is allowed to declare even private destructors for statically constructed objects.
Here is my code snippet for Singleton:
class Singleton
{
public:
static Singleton& GetInstance();
// Before C++ 11
private:
Singleton() {}
~Singleton() {}
Singleton(const Singleton&); // Without implementation
Singleton& operator=(const Singleton&); // Without implementation
// Since C++ 11
private:
Singleton() = default;
~Singleton() = default;
public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
Singleton& Singleton::GetInstance()
{
static Singleton instance;
return instance;
}
All classes have a destructor. If you don't create one the compiler will do so for you. So your question can be reworded to: Does the destructor for a singleton class have to private?
The simple answer is no, it doesn't have to be.
A more interesting question: Is it a good idea to make the destructor of a singleton class private?
Yes, in general, it is a good idea. If you make it private then your client code won't call the destructor by accident. Calling the destructor would cause the singleton to fail for all clients as the instance would become invalid.
No, and in general objects in C++ are not given private destructors. Keep in mind that Singleton means that there is only one instance, and so it is construction, not destruction, that needs to be controlled / prevented. Usually a singleton has a private constructor, a public destructor, a private static instance variable, and a public static singleton get / lazy construction function, although there are variations on that pattern.
You may return reference to your singleton instance.
class Factory : public IFactory
{
private:
/**
* This class should not be instantiated through its constructor. Since, it implements
* Singleton pattern.
*/
Factory();
public:
virtual ~Factory();
/**
* Accessor method for singleton instance.
* \note use this static method to access to operations of this class.
*/
static IFactory& instance(){
if(!m_instance.get()){
m_instance.reset(new Factory());
}
return static_cast<IFactory&>(*m_instance);
}
/**
* \see IFactory::create
*/
virtual boost::shared_ptr<IConnector> create();
private:
/* Singleton instance */
static boost::scoped_ptr<Factory> m_instance;
};
Having a private destructor as part of a singleton is not required from a programmer's point of view, but essential from a design point of view.
It avoids misuse of the class.
However, if you add a private destructor, you have to instantiate your class:
In a function / method: because if you create it as a global variable, you lose the interest of using a singleton (created to avoid global variables).
With the correct way to instantiate it: if your destructor is private, your class could not be deleted at the end of your program if you instantiate it as a "classic" local variable, because it can't access to it. So you have to instantiate it like this :
Singleton * potatoe = &Singleton::getInstance();
Here, we create a weak pointer named "potatoe", wich correspond to the address of the result of the "getInstance" function.
The consequence is that the destructor will not be called at the end of the function. But because (in "getInstance") the variable is declared "static" in a "static" method, the destructor will be called at the end of the program, without you having to do it.
Here is my code. Feel free to comment it.
// "class.hpp" file
class Singleton {
public:
static Singleton& getInstance() {
static Singleton S;
return S;
}
private:
Singleton();
~Singleton();
};
// "main.cpp" file
#include "class.hpp"
int main()
{
Singleton * patatoe = &Singleton::getInstance();
Singleton * tomatoe = &Singleton::getInstance();
Singleton * salad = &Singleton::getInstance();
return 0;
}