Boost logo

Boost Users :

From: Simon Buchan (simon_at_[hidden])
Date: 2005-10-13 04:32:16


Matthias Kaeppler wrote:
> Hello,
>
> I have two questions regarding the proper use of boost::shared_ptr; both
> actually arose after reading
> http://www.boost.org/libs/smart_ptr/example/shared_ptr_example.cpp
<snip 1>
> 2. In your examples, sometimes you're passing a shared_ptr by value, and
> sometimes by reference-to-const. Which is the better practice? Usually,
> common pointers are passed by value, but since in shared_ptr a reference
> counting mechanism keeps track of the copies, maybe it's better to pass
> it by reference whenever possible?

To sum up the costs (assuming raw pointer + count pointer impl):
by ref:
address-of
push dword

/de-ref per usage *on top of shared_ptr access*/

by val:
de-ref
incr
push 2 dwords

/normal usage/

de-ref
decr

As all of these are trivial CPU operations, both ways are very cheap,
but since trivial usages will often be inlined, and complex usages in
inner loops can be amortized (I've always wanted to say that :-) (the
result of the reference de-ref or shared_ptr de-ref can be kept in a
register), there can be /no/ difference in cost. So you're left with
taste. Personally, I think a reference to a pointer is _always_ pretty
ugly (but occasionally useful).


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