Search This Blog

Saturday, October 31, 2009

C++, Meyers' Singleton


#include
using namespace std;

class single {
public:
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:
//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();
mysingle->print();
}


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 a.cc,
Person B initialize the static variable in b.cc
what if, there is another static variable in another class,
and the order of initialization is important?

reference:
E.C++, Item 4, initialize the object before they are used
http://stackoverflow.com/questions/389779/should-i-use-static-data-members-c

No comments: