I have the following singletone implementation:
class B
{
public:
static B *getInstance()
{
if ( !m_data )
m_data = new(std::nothrow) B;
return m_data;
}
private:
static B *m_data;
private:
B() { std::cout << "B::B() " << B::m_data << std::endl; }
~B() { std::cout << "B::~B()" << std::endl; }
B( const B & ) = delete;
B &operator=( const B & ) = delete;
};
B *B::m_data = nullptr;
In main() I have:
B *pSingletone = B::getInstance();
I was surprised to see that destructor was never called after I killed my program. What am I missing? Do we need destructor at all in this case? My questions are about destructor only, not how bad or good singletons are. I know I don't have to allocate it on the heap.
Edit to summarize: as several people pointed out, only static pointer is destructed on program termination, not the object it pointed to. To destruct the object, explicit "delete" is needed. After the program terminated, the allocated memory is of course returned to the system but without destructor call. Thanks everybody!