This line
Singleton inst = Singleton::getInstance();
Must be
Singleton& inst = Singleton::getInstance();
Then you will see only one call to the destructor.
The write method, Singleton::getInstance() returns the link, and then copies to inst . Thus, as Singleton returned from your function , so , the copy is destroyed. You never saw a copy to be built because the default constructor was not used, the copy constructor was.
The second method returns a link, then you just inst should be a link to Singleton instead of creating a copy.
As already mentioned, you can make the class not copied and immovable to prevent this
Singleton(Singleton const&) = delete; // Copy construct Singleton(Singleton&&) = delete; // Move construct Singleton& operator=(Singleton const&) = delete; // Copy assign Singleton& operator=(Singleton &&) = delete; // Move assign
source share