tags:

views:

96

answers:

2

Or if i need to do that, then i should just use shared_ptr?

I know i have many questions regarding smart pointer - i still don't quite understand when to use which smart pointer.

+5  A: 
Nikolai N Fetissov
Do you think it is OK to just pass the pointer itself to the other method?I mean: if in f1 i allocated shared_ptr<A> a (new A()), is it good practice to do: f2(a.get()).of course, f2 receives pointer to A here.
amitlicht
Event better - pass a [const] reference: `f2(*a);`.
Nikolai N Fetissov
you mean *(a.get())?
amitlicht
I mean `T ` of `scoped_ptr`.
Nikolai N Fetissov
+3  A: 

Yes you can pass it by reference.

However, if the function just wants to use the managed object, you might consider passing a reference to the object itself.

void foo(const boost::scoped_ptr<Object>& o)
{
     o->foobar();
}

void bar(const Object& o)
{
     o.foobar();
}

The difference is that in the first case you have coupled the function with a particular smart pointer type.

Object o;
boost::scoped_ptr<Object> scoped(new Object);
boost::shared_ptr<Object> shared(new Object);

foo(o);  //no
foo(scoped); //OK
foo(shared); //no

bar(o);  //OK
bar(*scoped); //OK
bar(*shared); //OK

Generally I'd only pass the scoped_ptr, if the intention is to do something with the scoped_ptr instance itself (e.g release or reset the resource). Similarly for shared_ptr (e.g the function wants to share the resource with other shared pointers).

UncleBens