|
-
July 23rd, 2009, 07:57 AM
#3
Re: Singleton class and static data members of the class type
 Originally Posted by seventhirty
This code, as it is compiles fine, but singleton(the static object) is never created ( i think..)
If you define it in a cpp file, it is created when the program starts up, before main() is executed.
I suppose, as any other static data member, singleton must be defined exactly once outside the class body. How do I do that with a private constructor?
Code:
#include "Singleton.h"
Singleton Singleton::singleton;
I suppose I should define a public static function that:
1. creates dynamically an object if there is no object created
2.returns a reference to it..
That's a different design for a singleton. It has it's benefits (singleton object is not created if it is never called, multiple singletons can be dependend on each other during initialization), but it is also much harder to implement. A good implementation can be found in the Loki library.
With the design you have, you just need a static member function that will return a reference to the one-and-only object.
If i define only one constructor that is private, how can I initialize the class static member, which is an object of the same type as the class itself outside the class definition?
The static object is defined within the scope of the Singleton class. Therefore, it has access to the private constructor.
Cheers, D Drmmr
Please put [code][/code] tags around your code to preserve indentation and make it more readable.
As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|