Boost logo

Boost Users :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2005-08-27 12:10:34

Matthias Kaeppler wrote:
> Hi,
> I was wondering why e.g. boost:shared_ptr has an explicit constructor.
> This makes automatic conversion from T* to shared_ptr<T> impossible.

Correct, the intent of the explicit constructor is to disable implicit
conversions from T*.

> The lack of the opposite conversion is covered by the FAQ and
> reasonable; however, I couldn't think of a good reason why I shouldn't
> be able to do something like this:
> std::set< boost::shared_ptr<Foo> > coll;
> coll.insert(new Foo);

One reason is that the pointer constructor assumes ownership of the pointer
and as such, it imposes the requirement that the pointer has to be

The design of shared_ptr is based on the premise that the user assumes the
responsibility of constructing the shared_ptr with a valid pointer (and not
invalidating the pointer afterwards). In return, shared_ptr promises that
the rest of the operations are safe and the passed pointer will be deleted
exactly once, using its original type.

Therefore, when doing a code review, you have to concentrate on shared_ptr
constructors (and the reset alias). For this to be possible, you have to be
able to locate them easily. If shared_ptr had an implicit constructor, all
kinds of innocent statements of the form

coll.insert( p );

could potentially create a shared_ptr, making the review much harder.

For another reason, see the Best Practices section of the documentation.

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at