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


Hi!

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:
bla(boost::ref(bla_ptr));

>
> 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
{

  Bar()
      : data_()
  {}

  ~Bar()
  {
      *data_ = 100;
  }

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

private:
  int* data_;
};

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

     bar.set(ptr);
} // 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
sp.

Ovanes



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