Singleton Destructors

后端 未结 12 1732
一整个雨季
一整个雨季 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

    As so often, "it depends". In any operating system worthy of the name, when your process exits, all memory and other resources used locally within the process WILL be released. You simply don't need to worry about that.

    However, if your singleton is allocating resources with a lifetime outside it's own process (maybe a file, a named mutex, or something similar) then you do need to consider the appropriate cleanup.

    RAII will help you here. If you have a scenario like this:

    class Tempfile
    {
    Tempfile() {}; // creates a temporary file 
    virtual ~Tempfile(); // close AND DELETE the temporary file 
    };
    
    Tempfile &singleton()
    {
      static Tempfile t;
      return t;
    }
    

    ...then you can be reassured that your temporary file WILL be closed and deleted however your application exits. However, this is NOT thread-safe, and the order of object deletion may not be what you expect or require.

    however, if your singleton is implemented like THIS

    Tempfile &singleton()
    {
      static Tempfile *t = NULL;
      if (t == NULL)
        t = new Tempfile(); 
      return *t;
    }
    

    ... then you have a different situation. The memory used by your tempfile will be reclaimed, but the file will NOT be deleted because the destructor will not be invoked.

提交回复
热议问题