Singleton Destructors

后端 未结 12 1734
一整个雨季
一整个雨季 2021-01-31 03:55

Should Singleton objects that don\'t use instance/reference counters be considered memory leaks in C++?

Without a counter that calls for explicit deletion of the singlet

12条回答
  •  天涯浪人
    2021-01-31 04:32

    How are you creating the object?

    If you're using a global variable or static variable, the destructor will be called, assuming the program exits normally.

    For example, the program

    #include 
    
    class Test
    {
        const char *msg;
    
    public:
    
        Test(const char *msg)
        : msg(msg)
        {}
    
        ~Test()
        {
            std::cout << "In destructor: " << msg << std::endl;
        }
    };
    
    Test globalTest("GlobalTest");
    
    int main(int, char *argv[])
    {
        static Test staticTest("StaticTest");
    
        return 0;
    }
    

    Prints out

    In destructor: StaticTest 
    In destructor: GlobalTest
    

提交回复
热议问题