Boost logo

Boost Users :

From: Douglas Gregor (gregod_at_[hidden])
Date: 2003-03-28 11:52:00


On Friday 28 March 2003 11:36 am, Maurizio Colucci wrote:
> It seems that the reason is the explicit keyword in the
> constructor. My question is: why? what was the danger without the
> explicit?

The shared_ptr<T>(T*) takes ownership of the object referenced by the pointer.
Whenever you have an implicit conversion that may take ownership, you're
opening yourself up to the possibility that the programmer may not realize
ownership has been transferred. For instance:

void f(shared_ptr<T> x);
// later on, possibly from a different programmer...
T* t = new T;
f(t);
delete t;

The programmer that writes the last three lines doesn't realize that passing a
raw pointer results in the loss of ownership of the object, and now we have a
double-free. The explicit construction makes the programmer think about the
effects of calling a constructor, so this error is much less likely.

Even worse, consider trying to update some code that used to use raw pointers
to use shared_ptrs. Errors like the above would be common, but wouldn't be
found at compile time.

        Doug


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net