Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static local variable in C++11?

What is the difference between:

class A {
 public:
   static const A& GetInstance() {
     static A a;
     return a;
   }
};

and

class B {
  public:
   static const B* GetInstance() {
     static B* b = new B;
     return b;
   }
};

? Is there a difference in the lifetime of the Singleton between A and B? the memory location of the object? any differences generally?

like image 234
iBrAaAa Avatar asked Feb 09 '23 00:02

iBrAaAa


1 Answers

The lifetime of the object in these two cases is different. C++ guarantees that static local objects will be destroyed in reverse order to their construction. In both cases, construction will happen when GetInstance is first called.

However, in the second case, the variable b was assigned a pointer allocated with new. When b is removed from static storage, that memory will remain until the heap is finally torn down. At that stage it would be considered "leaked", and the destructor (if any) for B will never be invoked.

It would be better to implement the pointer-based approach like this:

class B {
  public:
   static const B* GetInstance() {
     static std::unique_ptr<B> b( new B );
     return b.get();
   }
};

Now, B::~B() will be invoked (if applicable) and that memory will be correctly removed when b is destroyed, and the lifetime is the same as your first example.

That just leaves your question about memory location. The location will be different. Static variables are generally stored in the program's data segment, whereas anything allocated with new will be stored in the heap.

like image 184
paddy Avatar answered Feb 16 '23 02:02

paddy