The below code snip from a singleton class(claiming to be!!) is used for returning the singleton instance of the class using reference. The copy/move constructors were not marked as deleted in this case.
static SingletonTestClass& getInstance() {
static SingletonTestClass handler;
return handler;
}
And there were two flavours of usages as follows
- Getting the instance to a local variable and use that to invoke class functions
auto handler = SingletonTestClass::getInstance();
handler.someApi();
- Directly calling the "someApi" like shown below.
SingletonTestClass::getInstance().someApi();
For case 1 there is a copy constructor involved wherein in case of 2 its not. I am interested in knowing how case 2 is working inernally.
Note: I have refactored the original code to the following style assuming this is a good way of implementing singleton and would like to know if there is a better way to do this.
public:
static SingletonTestClass* getInstance() {
static SingletonTestClass handler;
return &handler;
}
/* Note: Do not provide copy/move semantics */
SingletonTestClass(const SingletonTestClass& ref) = delete;
SingletonTestClass(SingletonTestClass&& ref) = delete;
~SingletonTestClass() = default;
Well it is according to the specification of the language. The
SingletonTestClassinstancehandlerwhichgetInstance()initializes on the call stack is initialized once and only once and it is given static storage duration.So it lives through out the lifetime of the program and will only be destructed upon program exit.