Stuart Golodetz
11/1/2008 11:21:00 PM
Hendrik Schober wrote:
> Marcel Müller wrote:
>> Hi,
>>
>> ..rhavin grobert schrieb:
>>> __________________________________________________
>>> void obj::foo(shared_ptr<>); vs. void obj::foo(shared_ptr<>&);
>>>
>>> and
>>>
>>> shared_ptr<>& obj::foo2(); vs. shared_ptr<> obj::foo2();
>>> __________________________________________________
>>
>> well, in this case it is up to you to ensure the livetime of the
>> referenced object.
>>
>> In general returning a reference to a shared_ptr is a bad advice,
>> since shared_ptr is explicitly designed to manage object lifetime in
>> situations like this. And the copy constructor of shared_ptr is quite
>> cheap, since it is always only a reference to your object.
>
> That depends. Incrementing/decrementing reference counts
> need to be seen by all processors on multi-processors
> architectures, so it requires access to the main memory,
> rather than to the cache. Depending on what your program
> does, that could be quite expensive.
> I do, however, agree that, when you pass a const ref to
> a smart pointer, you should probably be passing a const
> ref to the object instead.
I guess it depends on what you want to do with the thing you're passing
in. If you're just accessing it, then passing a const ref to the object
makes sense (though arguably no more sense than passing a const ref to
the shared_ptr, if that's what you've got); if you need to store the
object, then passing a const ref to the shared_ptr may be a much better
idea - if you pass a const ref to the object, the only way to store it
is to make a copy, which can be expensive/in some cases (if the copy
constructor is inaccessible) impossible. Copying the shared_ptr, on the
other hand, is generally far less expensive (even if we eschew the
debate about whether or not it is actually 'cheap', for some definition
of cheap).
As a side point, btw, it's worth noting that the const semantics of
passing a const ref to the shared_ptr and a const ref to the object are
different: if you pass a const ref to the shared_ptr, you can change the
object it points to but not the shared_ptr. It's like the distinction
between const X& and X *const. To get the same semantics, you probably want:
const shared_ptr<const X>&
It's also worth noting that there's a conversion:
shared_ptr<X> -> shared_ptr<const X>
So you can pass a shared_ptr<X> to a function which expects a
shared_ptr<const X>.
Stu
> (OTOH, I recently modified a
> piece of library cod to use smart pointers instead of
> dumb ones and did not evaluate all function signatures
> for whether passing an object instead of a pointer would
> have been better. Instead I passed smart pointers per
> const ref where applicable.)
>
>> [...]
>> Marcel
>
> Schobi