How to call destructor of singleton classes without CRT

65 views Asked by At

I am developing a program without the C runtime library (CRT) with C++ as a fun little challenge. As part of this challenge I ended up writing my own atexit() function which is called whenever main returns.

This function works as expected and calls the destructor of most classes, with a caveat: I have to manually run all destructor functions (they are stored in a linked list, and executed in a last-in, first-out (LIFO) order) before my main function terminates. If anybody knows a better way, do let me know, but that's a separate issue.

My main problem is that while debugging, I found out that the destructor of my singleton classes are not being called, and I'm trying to figure out why. I am new to C++, please don't bully me.

Code example of singleton:

/*socket_manager.h*/
class SocketManager {
    // static instance variable here
    static SocketManager* instance;
    ~SocketManager() {
        // close socket/do cleanup, this is what I'm trying to get to run
     }

public:
    static SocketManager* getInstance();
}


/*socket_manager.cpp*/

// global variable for instance, set to nullptr
SocketManager* SocketManager::instance = nullptr;

// creates new SocketManager if instance is null, else returns instance
SocketManager *SocketManager::getInstance() {
    if (instance == nullptr) {
        instance = new SocketManager();
    }
    return instance;
}

Essentially: What am I doing wrong? How do I make sure the destructor for this singleton is executed on program termination, without the STL/CRT?

0

There are 0 answers