Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2004-11-11 20:03:03


Dirk Gregorius wrote:
> I have four easy questions regarding boost::shared_ptr:
>
> 1.) How do I pass a boost::shared_ptr to a function - via value or
> reference?
>
> void ByValue( boost::shared_ptr<Foo> pFoo );
> void ByReference( boost::shared_ptr<Foo>& rFooPtr );

By value when the function wants to modify its own temporary copy of the
argument; by const reference or by value (slightly less efficient, but often
unnoticeable) when it's an immutable input argument; by non-const reference
when it's an output argument. Same as with any other "medium-weight" type.

> 2.) When passing a raw pointee to a function you can declare the
> pointee const. How do I pass a const boost::shared_ptr?
>
> void ConstRaw( const Foo* pFoo );
> void ConstSharedPtr( ??? );

shared_ptr<Foo const> pFoo

> 3.) Does anything speak against passing a reference to a factory
> function instead of returning the boost::shared_ptr?
>
> boost::shared_ptr<Foo> Create( void )
> {
> return boost::shared_ptr<Foo>( new Foo );
> }
>
> bool Create( boost::shared_ptr<Foo>& foo )
> {
> // Make some validations and return false on error.
> // ...
>
> // Everyting is ok. Reset the pointee and return a success
> foo.reset( new Foo );
>
> return true;
> }

No, but you can indicate failure by returning an empty shared_ptr from the
first Create.

if( shared_ptr<Foo> p = Create() )
{
    // do something
}
else
{
    // Create failed
}

> 4.) Can I test a boost::shared_ptr against NULL like a raw pointee?

Yes, the conversion operator that enables if( p ) tests also enables p == 0
comparisons as a side effect.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk