Static local variable in C ++ 11?

What's 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 Singleton's lifetime between A and B? object memory location? any differences whatsoever?

+4
source share
2 answers

The lifetime of an object in these two cases is different. C ++ ensures that static local objects will be destroyed in the reverse order before they are built. In both cases, construction will occur when it GetInstanceis first called.

b , new. b , , . "", ( ) b .

:

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

B::~B() ( ) , b , , .

. . , , new, .

+8

, 2 ( , ).

  • /, 2 , ( ). ++ /, .
  • . nullptr .

EDIT: SO, ref : / Singleton ++

0

Source: https://habr.com/ru/post/1624904/


All Articles