Reputation: 3738
Imagine I create an instance of Foo on the heap in a method/function and pass it to the caller. What kind of smartpointer would I use?
smartptr new_foo() {
smartptr foo = new Foo();
return foo;
}
void bar() {
smartptr foo = new_foo();
foo->do_something();
// now autodelete foo, don't need it anymore
}
Ok... now: As far as I understand those smartpointers from boost, scoped_ptr should be the one to be used in bar(). But I can't create it in foo(), as it's not copyable. So I have to create a shared_ptr in foo() and return it. But do I now have to use a shared_ptr in bar(), or can I just "cast" it to an shared_ptr in bar()?
Edit
Thanks for your answers so far! So now I got two solutions:
boost::shared_ptr
std::auto_ptr
in the generator foo() and boost::shared_ptr
in bar()Sincerely, I prefer a boost-only solution and won't mix it with STL except there is really a good reason for doing so. So, next question: has the mixed solution any advantage over the boost only solution?
Upvotes: 2
Views: 1379
Reputation: 13994
boost docs suggest they don't mix
If you are transfering ownership then another option at the moment would be auto_ptr e.g.
smartptr new_foo() {
std::auto_ptr<Foo> foo = new Foo();
return foo;
}
void bar() {
std::auto_ptr<Foo> foo = new_foo();
foo->do_something();
// now autodelete foo, don't need it anymore
}
however this will then restrict how you can use new_foo() i.e. you can't use it to fill a container (without managing the resource some other way). :(
With C++0x and rvalue references this will be a job for unique_ptr, which will replace auto_ptr and just do what you want
Upvotes: 2