N
Noah Roberts
Some little tidbit I just ran into that might help some, especially
novice programmers.
If you are using the pimpl idiom, as you probably should be most of the
time, then it is very straightforward to turn your class into a
singleton object. Consider:
class X
{
struct impl;
boost::scoped_ptr<impl> pimpl;
public:
X();
~X();
void f();
}
X::X() : pimpl(new impl){}
X::~X() {}
void X::f() { pimpl->f(); }
To turn that into a singleton just do the following:
1. turn pimpl into a static member.
2. Initialize it in the cpp file as usual.
3. you're done.
You could change it so that the constructor is private and you have an
instance() function but why bother?
X x;
x->f();
Creating the x object is of minimal expense. You may later decide a
singleton isn't a good way to solve the problem. None of your client
code would need to be changed.
There may be some extra bookkeeping to do of course so you might need
some initializer function that is called once. This is pretty easy to
do and can be just built into or called from the constructor.
novice programmers.
If you are using the pimpl idiom, as you probably should be most of the
time, then it is very straightforward to turn your class into a
singleton object. Consider:
class X
{
struct impl;
boost::scoped_ptr<impl> pimpl;
public:
X();
~X();
void f();
}
X::X() : pimpl(new impl){}
X::~X() {}
void X::f() { pimpl->f(); }
To turn that into a singleton just do the following:
1. turn pimpl into a static member.
2. Initialize it in the cpp file as usual.
3. you're done.
You could change it so that the constructor is private and you have an
instance() function but why bother?
X x;
x->f();
Creating the x object is of minimal expense. You may later decide a
singleton isn't a good way to solve the problem. None of your client
code would need to be changed.
There may be some extra bookkeeping to do of course so you might need
some initializer function that is called once. This is pretty easy to
do and can be just built into or called from the constructor.