CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13
  1. #1
    Join Date
    May 2012
    Posts
    0

    Singleton Method

    Hi All,

    Please suggest me the link or sample code for the singleton method.

    1) Need to create single instance and need to use that instance in entire project.
    2) Should not allow to create new instance.
    Code:
    #include <stdio.h>
    #include <iostream>
    using namespace std;
    class Sample
    {
    	private:
    	int test;
    	public:
    	int setValue(int a)
    	{
    		test=a;
    	}
    
    	int getValue()
    	{
    		cout<<"test value = "<<test;
    	}
    };
    class CMySingleton
    {
    
    
    	private:
      	CMySingleton() {};   
    	static Sample *singleton;
    
    	public:
      	static Sample* Instance()
      	{
    		singleton=new Sample();
    	    	return singleton;
      	}
    
    
    
    };
    int main()
    {
    	Sample *obj=CMySingleton::Instance();
    	cout<<"\n "<<&obj;
    	Sample *obj1=CMySingleton::Instance();
    	cout<<"\n "<<&obj1;
    	return 0;
    
    }
    It throws error

    /tmp/ccFuSDhv.o: In function `CMySingleton::Instance()':
    singleton.cpp.text._ZN12CMySingleton8InstanceEv[CMySingleton::Instance()]+0x17): undefined reference to `CMySingleton::singleton'
    singleton.cpp.text._ZN12CMySingleton8InstanceEv[CMySingleton::Instance()]+0x1e): undefined reference to `CMySingleton::singleton'

    Thanks
    -Viswa

  2. #2
    Join Date
    Mar 2001
    Posts
    2,529

    Re: Singleton Method

    To Fix your sample, you will need to add the line in bold.
    Code:
    	static Sample* Instance()
      	{
    		singleton=new Sample();
    	    	return singleton;
      	}
    
    
    
    };
    Sample *CMySingleton::singleton = NULL;
    There are faqs in CG that cover singleton.

    HTH,
    ahoodin
    To keep the plot moving, that's why.

  3. #3
    Join Date
    Jan 2009
    Posts
    1,689

    Re: Singleton Method

    That's not a good idea. Singletons should clean themselves up, if you create your singleton on the heap, then you are supposed to delete it.

    Code:
    static Sample & Instance(){
         Sample singleton;
         return singleton;
    }
    Here it gets initialized on first call, and gets automatically destroyed properly when the program exits. It also eliminates the need for a global.

  4. #4
    Join Date
    Mar 2001
    Posts
    2,529

    Re: Singleton Method

    Give him a break.

    They need to learn, and the way he is doing it is a simple singleton pattern.

    http://forums.codeguru.com/showthread.php?t=344782
    Last edited by ahoodin; May 3rd, 2012 at 08:32 AM.
    ahoodin
    To keep the plot moving, that's why.

  5. #5
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Singleton Method

    Quote Originally Posted by ninja9578 View Post
    That's not a good idea. Singletons should clean themselves up, if you create your singleton on the heap, then you are supposed to delete it.

    Code:
    static Sample & Instance(){
         static Sample singleton;
         return singleton;
    }
    Here it gets initialized on first call, and gets automatically destroyed properly when the program exits. It also eliminates the need for a global.
    Err... with an extra static in there... right?
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  6. #6
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Singleton Method

    That's the basic idea, but remember you want to create only a single instance, so you check if singleton is null first:
    Code:
    	public:
      	static Sample* Instance()
      	{
    		if(!singleton)
    			{singleton=new Sample();}
    	    	return singleton;
      	}
    There are as many ways to write a singleton as fingers on your hand. Don't worry about it too much, as long as you have something working.
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  7. #7
    Join Date
    Mar 2001
    Posts
    2,529

    Re: Singleton Method

    Yes that is correct MD. Nice catch!
    ahoodin
    To keep the plot moving, that's why.

  8. #8
    Join Date
    May 2007
    Posts
    811

    Re: Singleton Method

    Quote Originally Posted by monarch_dodra View Post
    That's the basic idea, but remember you want to create only a single instance, so you check if singleton is null first:
    Code:
    	public:
      	static Sample* Instance()
      	{
    		if(!singleton)
    			{singleton=new Sample();}
    	    	return singleton;
      	}
    This will fail in multithreaded environment.

  9. #9
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Singleton Method

    Quote Originally Posted by STLDude View Post
    This will fail in multithreaded environment.
    Are you singling out my implementation specifically? Because the entire pattern is not thread safe, so its not like there's an alternative.
    Last edited by monarch_dodra; May 3rd, 2012 at 10:22 AM.
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  10. #10
    Join Date
    Jan 2009
    Posts
    1,689

    Re: Singleton Method

    Oops, I missed a static.

    In multithreaded environments, it is most common (that I've seen) to call all of the singleton methods in main() before any threads get launched.

  11. #11
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: Singleton Method

    The static one is thread safe in C++11 if I don't remember wrong.
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  12. #12
    Join Date
    May 2007
    Posts
    811

    Re: Singleton Method

    Quote Originally Posted by S_M_A View Post
    The static one is thread safe in C++11 if I don't remember wrong.
    You are right:

    ยง 6.7.4
    .. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.

  13. #13
    Join Date
    Jan 2009
    Posts
    1,689

    Re: Singleton Method

    Actually, now that I think about it. LLVM has an option for thread-safe statics too, even without C++11.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured