Boost logo

Boost Users :

Subject: Re: [Boost-users] shared_ptr as reference argument
From: Ovanes Markarian (om_boost_at_[hidden])
Date: 2009-03-19 12:20:23


On Thu, Mar 19, 2009 at 4:57 PM, anony <janezz55_at_[hidden]> wrote:

> Is there some utility in passing shared_ptr's as references as here:
> void bla(boost::shared_ptr<T>& bla_ptr);

Yes, boost::reference_wrapper. You might use it as follows:

> This avoids creating of a new object and copying overhead, but is it
> safe? When would you recommend it and when not?

It depends on the calling context... If you can ensure, that the pointer
reference is not stored and the calling function lives longer as the called
function (might happen during asynchronous calls) it is safe. Otherwise it
is not. Here an example:

struct Bar

      : data_()

      *data_ = 100;

  void set(shared_ptr<int> const& data)
    data_ = data.get();

  int* data_;

//possible misuse
void foo()
     Bar bar;
     shared_ptr<int> ptr = shared_ptr<int>(new int(10));

} // BOOM!!! => ptr is destroyed before the Bar::~Bar() is called

If you do not program real time soft, it is probably always better to copy


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