Search This Blog

Saturday, October 31, 2009

C++, Meyers' Singleton

using namespace std;

class single {
static single* get_instance()
//local static only get called the first time
// subsequent call to get_instance() will just return!
static single* local_static_single = new single;
return local_static_single;

void print() {cout<<"print";}

//private construction, assignment, etc
single() {cout<<"single constructor called"<
//no implementation, so even friend will fail at link-time
single(const single&);
single& operator=(const single&);

int main()
//only one single instance is constructed!
single* mysingle = single::get_instance();
single* mysingle2 = single::get_instance();
single* mysingle3 = single::get_instance();

this trick can help you initialize your static variable in certain order.
if you don't, then the order of initialization static variable is UNDEFINED across
DIFFERENT translation unit.
e.g. Person A initialize the static variable in,
Person B initialize the static variable in
what if, there is another static variable in another class,
and the order of initialization is important?

E.C++, Item 4, initialize the object before they are used

No comments: