Hi, I have a question that I believe is more a matter of taste than one of functional correctness... Say that I have a model (see Basket below) that formally owns the heap-objects (see Apple below). Basket has a function that is merely a query (hasApple) and involves no ownership-changes. Also assume that there is good reason that Apple:s are allocated on the heap... On one hand, I can see how using a weak_ptr as the parameter type would signal to users that hasApple has no intention of modifying ownership of the pointed-to object. On the other hand, in order to actually use the pointee (search for it in this case), hasApple must convert the weak_ptr to shared_ptr (lock() or shared_ptr constructor), so it would seem more pragmatic to just use shared_ptr as the parameter type. class Apple; class Basket { std::vector< boost::shared_ptr<Apple> > m_contents; bool hasApple( shared OR weak_ptr<Apple> a); // no transfer ...more functions }; Is there a "good style" concensus on how to choose smart pointer type for function arguments among boost smart pointer users? Best regards, Niklas Wiberg
G'day.
Quoting Niklas Wiberg
Basket has a function that is merely a query (hasApple) and involves no ownership-changes. [...] On one hand, I can see how using a weak_ptr as the parameter type would signal to users that hasApple has no intention of modifying ownership of the pointed-to object.
No, because weak_ptrs can be turned into shared_ptrs. What you want in this case is an unmanaged pointer. That is, you want a raw, dumb, C-style pointer. Think about it for a moment. If hasApple() truly does not manage the lifetime of the Apple which it is passed, then presumably its lifetime is already being managed by the caller (or someone further up the call chain). Hence, it will exist for the duration of the call to hasApple(), so a raw pointer is safe. It's also better documentation. Use an unmanaged pointer for something that doesn't need to be managed. BTW, as a rule of thumb, passing a weak_ptr is almost always the wrong thing to do. The biggest exception, of course, is passing a weak_ptr by non-const reference expecting the callee to fill it in. There are other exceptions, but IME they're quite rare. Cheers, Andrew Bromage
participants (2)
-
ajb@spamcop.net
-
Niklas Wiberg