On Thu, Mar 19, 2009 at 12:17 PM, Steven Watanabe
anony wrote:
Is there some utility in passing shared_ptr's as references as here: void bla(boost::shared_ptr<T>& bla_ptr); This avoids creating of a new object and copying overhead, but is it safe? When would you recommend it and when not?
Why wouldn't it be safe? Unless the function stores a pointer or reference to the shared_ptr after it returns, there is no danger.
That's not really sufficient to be totally safe. Code like this could fail too: void do_work(some_shptr const & myobj) { std::cout << *myobj << '\n'; do_something(); std::cout << *myobj << '\n'; // oops (?) } Suppose that the shptr reference is invalidated in the call to do_something. This is entirely possible if the underlying object is owned by a global lookup table, and the caller of do_work() does not retain a reference to the object being passed in. When this happens, the global lookup table holds the only reference, and do_something might remove the element and invalidate the shptr.
From experience. :)
Chris