Boost logo

Boost :

From: Joe Gottman (jgottman_at_[hidden])
Date: 2006-03-24 19:43:47

"Vaclav Vesely" <vaclav.vesely_at_[hidden]> wrote in message
> Hi,
> In Best Practices section of shared_ptr is an example:
> void f(shared_ptr<int>, int);
> int g();
> void ok()
> {
> shared_ptr<int> p(new int(2));
> f(p, g());
> }
> void bad()
> {
> f(shared_ptr<int>(new int(2)), g());
> }
> Best Practices refers to (it deals with
> auto_ptr, but for shared_ptr the conclusion is same). The article
> proposes following solution:
> template<typename T, typename A1>
> shared_ptr<Type> new_shared_ptr(A1 a1)
> {
> return shared_ptr<Type>(new Type(a1));
> }
> void ok2()
> {
> f(new_shared_ptr<int>(2), g());
> }

   Another possible advantage of new_shared_ptr mentioned by the article is
that it could reduce the number of news required to create the shared_ptr
from 2 to 1. In the code
    shared_ptr<int> p(new int(7));
new is called twice: when the int is created and inside the shared_ptr's
constructor to construct an object of a type inheriting from
boost::sp_counted_base. The constructor is careful to maintain exception
safety, but some people might find the two calls to new to be inefficient.
The article suggested that new_shared_ptr could create an object containing
an int and an intrusive count, so that it would be unnecessary to call new
to create the int pointer.

   It would be possible to do this for boost::new_shared_ptr<T>, with a few
minor complications. Since boost::shared_ptr's separate the destruction of
the owned T pointer from the destruction of the shared_ptr infrastructure in
order to allow for weak_ptrs, the T would have to be created using placement
new, so that it would be possible to destroy it using placement delete when
the last shared_ptr is destructed.

Joe Gottman

Boost list run by bdawes at, gregod at, cpdaniel at, john at