Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2001-11-15 11:01:35


From: "Mattias Flodin" <flodin_at_[hidden]>
> I'd say there are more psychological reasons than this. I like to be able
> to express intent with source code rather than comments, when possible.

What is the advantage of using C++ instead of a natural language to express
intent? I can easily cite several drawbacks.

> In
> that respect, this code clearly communicates that "A isa singleton":
>
> class A : public singleton<A> {
> /* ... */
> };

Is this a library interface? If it is, why do you need the class name at
all? You know that there is a single instance of A.

Instead of

class A: public /* public? */ singleton<A>
{
    void f();
};

A::instance().f();

why not simply

namespace A
{
    void f();
}

f();

> Reliability is another simple reason for a singleton: you put your trust
> into singleton to handle whatever is necessary to make things work -
> instead of rewriting the singleton code each time, which would be more
> error-prone (especially when you need thread safety etc).

True. Reuse is an important tool.

> Furthermore there is a big difference between just a global variable and a
> singleton, in that the singleton may defer instantiation to the user, and
> thus provide a form of polymorphism.

So can a global scoped_ptr<A>.

> I may for instance have a virtual
> class Application, with the functions run() and process_handle(), the
> former being left to be implemented by the user:
>
> class Application : public singleton<A> {
> public:
> Handle process_handle();
> virtual int run()=0;
> private:
> /* ... */
> };
>
> And the user would make a concrete class that she instantiates:
>
> class MyApp : public Application {
> public:
> int run() {cout << "Hello World!" << endl; return 0;}
> };
> MyApp app;

MyApp looks like a global to me.

> IMHO policies are needed primarily because reality is not so theoretical
> as one would like it to be.

I agree, reality is not theoretical. Sometimes general principles are
overriden by tactical considerations - just like in chess.

But I'm not sure how the existence of policies would suddenly make something
practical.

For example, a policy-based singleton wouldn't (autmatically) solve some
practical lifetime problems that I encountered recently. I'd still need to
solve them manually.

My general point is, provide something simple that solves 85% of the
problems rather than something complex that solves 89% of the problems.

--
Peter Dimov
Multi Media Ltd.

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk