int main()
{
MySingleton&stobj=MySingleton::getInstance();
//some code here
}
Here What do I think is static MySingleton instance we have create will be in memory till program terminates.
Then if this is alive throught the life of the program why are we worrying about dead reference problem?
I have come across below code to ensure proper constrcution/destruction when we use meyers singleton
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class B
{
public:
static B& getInstance_Bglob;
{
static B instance_Bglob;
return instance_Bglob;;
}
~B()
{
A::getInstance_abc().doSomthing();
}
B()
{
A::getInstance_abc();
}
};
Then why in above program they are making sure that they have constrcued the object before so that its destruction is guaranteed to happen after the object from which they are calling.
Why do we have to worry about all this when these static instances are alive throut the program??
#include <iostream>
struct A
{
static A& instance() ;
int i = 7 ;
private:
A() { std::cout << "A::constructor\n" ; }
~A() { std::cout << "A::destructor\n" ; }
A( const A& ) = delete ;
A( A&& ) = delete ;
};
A& A::instance()
{
static A singleton ; // Meyers' singleton
return singleton ;
}
struct B
{
B() { std::cout << "B::constructor\n" ; }
~B()
{
std::cout << "B::destructor tries to access A::instance\n" ;
A& a = A::instance() ;
++a.i ; // use a
}
};
B b ; // B is constructed
int g = A::instance().i ; // Myers' singleton is constructed
// destruction of objects with static storage duration is in
// reverse order of constructon
// since the Myers' singleton was constructed after b,
// it would be destroyed before destructor of b executes
// and the destructor of b would get a dead eference
int main()
{
}