0

The following seems to be the recommended way to define a singleton in C++:

class Singleton {
private:

    Singleton();

public:
    static Singleton & get_instance() {
        static Singleton instance;
        return instance;
    }

     ~Singleton() {
        // destructor
     }

    Singleton(Singleton const&) = delete;
    void operator=(Singleton const&) = delete;
}

Now, take this function:

void foo() {
   Singleton & s = Singleton::get_instance();
}

I expected the destructor to be called when the singleton instance goes out of scope in that function, but it's not. When does the destructor get called?

jeffreyveon
  • 13,400
  • 18
  • 79
  • 129
  • 3
    Why would a destructor be called here? You just created a reference which then got destroyed. References are not proper objects and don't have destructors. – nwp Apr 27 '17 at 15:41
  • http://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function – Phil M Apr 27 '17 at 15:42

1 Answers1

3

No, the destructor won't be called since get_instance() returns a reference of the Singleton object, that reference is saved into s, another reference. Both of these references point to a static Singleton object, namely:

static Singleton instance;

So, there's only 1 object being worked on here, instance. Passing around references does not create new objects and thus does not invoke the destructor.

The object instance will be destroyed, and thus, it's destructor will get called at program termination (because it's static).

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
  • Specifically; the destructor will run after control flow leaves `main()` - but one should be aware that *order* of destruction is only well defined between statics within a single translation unit (see also: [What’s the “static initialization order fiasco”?](https://isocpp.org/wiki/faq/ctors#static-init-order) since the same applies to order of destruction). Singletons are *evil*. – Jesper Juhl Apr 27 '17 at 15:54
  • 1
    Thanks, I am new to C++. Let's say I have that singleton inside a HTTP server. What kind of interrupt should I send to my process for the destructor to fire? – jeffreyveon Apr 27 '17 at 15:55