Hi!
On Thu, Mar 19, 2009 at 4:57 PM, anony
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