Reputation: 394
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?
Upvotes: 4
Views: 1598
Reputation: 2703
Adding to the first answer, 2 comments (assuming you want to create a singleton).
EDIT: Here is an SO question where the answer contains relevant ref to standard: Heap/dynamic vs. static memory allocation for C++ singleton class instance
Upvotes: 0
Reputation: 63451
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.
Upvotes: 8