开发者

can scoped_ptr and shared_ptr be mixed?

开发者 https://www.devze.com 2023-01-15 01:06 出处:网络
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?

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开发者_StackOverflow中文版 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:

  • Use only boost::shared_ptr
  • Use 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?


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


Use boost::shared_ptr

0

精彩评论

暂无评论...
验证码 换一张
取 消