Meyers singleton--Dead reference problem...Please help

Hi I am going throuh Meyers singleton design pattern and the dead reference problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
class MySingleton
{
    private:
               MySingleton();
               MySingleton(MySingleton const& copy);
               MySingleton& operator=(MySingleton const& copy);
    public:
        static MySingleton& getInstance()
        {
            static MySingleton instance;
            return instance;
        }
};

if I write my main


1
2
3
4
5
6
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??

Please help

Thanks
Prasad
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#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()
{
}

http://coliru.stacked-crooked.com/a/fe4a48288fde2eb8
Thanks @JLBorges,I have got the context.
whats the meaning of these two lines,
1
2
  A( const A& ) = delete ;
        A( A&& ) = delete ;

No clue for me.

Thanks
Prasad
Topic archived. No new replies allowed.