Confusion Accessing Singleton Class Members

May 10, 2013 at 7:58pm
Hi, LeafyCircuits here!

Comp specs:
OS: Windows 7 Home Premium 64-bit
Compiler: GNU gcc with ISO and STL
IDE: Dev C++ ver 4.9.9.2 using C++11

I was playing around with the Singleton class design pattern, and I noticed something odd about accessing members of a Singleton that I'm confused about. Here's a basic Singleton class with one non-static member:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Singleton
{
      public:
             static Singleton *getInstance();
             int member;
      
      private:
              Singleton() {}
              ~Singleton() {}
              static Singleton *inst;
};

Singleton *Singleton::inst=0;
Singleton *Singleton::getInstance()
{
          if (inst==0) inst=new Singleton();
          else return inst;
}


In my code, when I tried to change the `member' var by doing this:
1
2
3
4
5
6
main()
{
      Singleton *test=Singleton::getInstance();
      (*test).member=5;
      getchar();
}


The program crashes. Debugging it later, the debugger says that an:
Access Violation (Segmentation Fault) raised in your program.


As soon as that assignment line executes. However, when I grab the Singleton instance again and re-store it in `test' again, like this:
1
2
3
4
5
6
7
main()
{
      Singleton *test=Singleton::getInstance();
      test=Singleton::getInstance();
      (*test).member=5;
      getchar();
}


Then this code works. What I don't understand is WHY this code works. When I instantiated the Singleton class with the first line, the address should have been stored in test, and the same address should be stored when I call the second getInstance() line. What's going on here? Any help would be very much appreciated.
May 10, 2013 at 8:07pm
Line 17. Why don't you want to return the instance that was just created on line 16?
May 13, 2013 at 6:28pm
keskiverto said:
Line 17. Why don't you want to return the instance that was just created on line 16?

Whoops. I do want to return that instance. Thanks for pointing that out; I didn't see that.
Topic archived. No new replies allowed.