1

In using the following Singleton implementation:

01  class Singleton
02  {
03  public:
04      static Singleton* Instance();
05   
06  protected:
07      Singleton();
08      Singleton(const Singleton&);
09      Singleton& operator= (const Singleton&);
10  };
11   
12  Singleton* Singleton::Instance()
13  {
14      static Singleton m_instance;
15      return &m_instance;
16  }

My question pertains to line 14.

Static methods normally operates on static variables, thus it is clear that the Instance() method operates on the static m_instance variable. But it seems that removing "static" from line 14 produces exactly the same result, i.e. only one instance is ever created.

Is it correct to assume that any variable declared inside a static method is automatically set as static?

ebann
  • 181
  • 6
  • The reason this works in [C++11 is because of concurrent access guarantee of a static variable](http://stackoverflow.com/q/27286444/1708801) – Shafik Yaghmour Mar 16 '15 at 17:57
  • 4
    If you remove `static` from line 14, you're returning the address of a local variable. It's a dangling pointer! – Brian Bi Mar 16 '15 at 18:01
  • If m_instance is an automatic variable in a static function it should be allocated in the stack frame of the function call to the function. Keeping that reference is officially not safe. When the stack gets cleaned up that memory may belong to someone else, and they can then change it. (I see Brian beat me to it.) – jobermark Mar 16 '15 at 18:01
  • 1
    @Brian is right, g++ even warns about this without `-Wall`. The consequently created Singleton objects might use the same address, that doesn't mean they are the same object. Calling the function twice still creates two objects – and also destroys them after the function finished. – jplatte Mar 16 '15 at 18:05
  • _"Is it correct to assume that any variable declared inside a static method is automatically set as static?"_ No, that assumption is wrong. If you remove the static keyword, you are returning the address of a local variable, and dereferencing it is leading to undefined behavior. – πάντα ῥεῖ Mar 16 '15 at 18:09
  • Also, if you don't use `static`, a new instance is created every time the function is called. `Singleton` is not a singleton class any more. – R Sahu Mar 16 '15 at 18:10
  • 1
    Singletons are evil enough to have occasionally kept me awake at night. But here's a horde of undead singletons: I may never sleep again. – Mike Seymour Mar 16 '15 at 18:53
  • Thanks for the clarification! They are all great answers. While this question was tagged as duplicate, I did not possess enough knowledge to link it with "local variable accessed outside scope", but now I can see that it is just that, and not limited to singletons. Dangling pointer... wow! Thanks again. – ebann Mar 17 '15 at 12:46

0 Answers0