Accessing singleton class instance

I am trying to understand different ways to access singleton class instance. Whats the right way to access singleton instance.

test.h
class test
{
private:
test();
static test* m_test;
public:
static test* getInstance();
}

test.cpp
test* test::m_test= NULL;
test* test::getInstance()
{
if (m_test == NULL)
m_test = new test();

return m_test;
}



and i am going to use it inside multiple files, now my query is what is the right way to access it.

test* testObj = testObj->getInstance();

vs

test* testObj = test::getInstance();
test::getInstance. testObj is trash when your trying to deref it.
Last edited on
Your getInstance() static member is not the best for making a singleton class instance. It just returns a pointer. This is bad, because there is nothing stopping the user from calling getInstance multiple times and receiving multiple class instance pointers.

Another solution could be like so:
1
2
3
4
5
6
7
8
9
class test
{
public:
    test* get_singleton() const {if(!Singleton) Singleton = new test; return Singleton;}
private:
    test() = default; //Private default ctor
    static inline test* Singleton = nullptr; //Single static member
};


Now whenever you need access to the singleton instance, you can use the get_singleton() method to access it. Also, you should try to avoid operator new in modern C++ especially with the advent of alternatives like smart pointers. I think you could also do this:
1
2
3
4
5
6
7
8
9
class test
{
public:
    test get_singleton() const {return Singleton;}
private:
    test() = default; //Private default ctor
    static test Singleton;; //Single static member
};
test test::Singleton{};
Last edited on
Why use a pointer at all?
test.h
1
2
3
4
5
6
7
class test
{
private:
    test() = default;
public:
    static test& getInstance();
}


test.cpp
1
2
3
4
5
test& test::getInstance()
{
    static test instance;
    return instance;
}


Personally, I've never needed a singleton in C++. Just make all the data static instead.
Last edited on
Topic archived. No new replies allowed.