|
Boost : |
Subject: Re: [boost] [shared_ptr] calling functions by reference
From: Matt Calabrese (rivorus_at_[hidden])
Date: 2011-05-28 22:53:28
On Sat, May 28, 2011 at 10:36 PM, Sid Sacek <ssacek_at_[hidden]>wrote:
> This might be a unimportant question and may have already been answered
> many times before, but I was wondering about functions that take shared
> pointers as arguments. Is there ever a reason I would not want to use a
> shared_ptr reference as an argument? I can't think of any, but is there any?
>
One common reason given to pass by value is to implicitly handle the case
where you call a separate function which may release your shared pointer as
a side effect. For instance:
//////////
shared_ptr< int > a( new int( 2 ) );
void foo()
{
a.reset();
}
void bar( shared_ptr< int > const& arg )
{
foo();
*arg = 0; // Kaboom
}
int main()
{
bar( a );
}
//////////
Note that while here the issue may seem obvious, similar problems can be
much more subtle in practice (for instance, you may be calling a
user-provided function object, etc.). If you had passed the smart pointer by
value then this code would not be problematic.
Still, it is my opinion that you should generally prefer passing by
reference, just as you would most other types with non-trivial copy
operations. Copying a shared_ptr is far from free. If you encounter a
situation similar to the above, then just copy the shared_ptr in that
particular case.
-- -Matt Calabrese
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk