returning a 'pointer' which is required to be held by a smart pointer

六月ゝ 毕业季﹏ 提交于 2019-12-02 19:40:21

Using std::auto_ptr is the good practice, in fact such example was suggested by Bjarne Stroustrup.

The move semantics of auto_ptr gives you right tools to deal with it.

For example:

auto_ptr<Foo> make_foo()
{
    return auto_ptr<Foo>(new Foo);
}

Foo *raw_pointer=make_foo().release();
shared_ptr<Foo> shared_pointer=make_foo();
auto_ptr<Foo> auto_pointer=make_foo();

If you return shared_ptr you can't fallback to normal pointer, with auto_ptr you can. You can allways upgrade auto_ptr to shared but not other direction.

Another important point, shared_ptr uses atomic reference-counting, that is much slower that simple and yet fully efficient job that auto_ptr does.

P.S.: scoped_ptr is just version of auto_ptr for poors --- it is non-copyable and does not have default constuctor. It is more like "less confusing" version of auto_ptr, in comparison to shared_ptr it is not in tr1. Generally there no much advantages of using scoped_ptr over auto_ptr

If you build a factory that's ok that you simply return a pointer. And the user of your factory can make his own decision how to and where to put this pointer.
If you need to enforce to use smart pointer you have to restrict choice as you don't want them to use "wrong" ones.
So boost::shared_ptr. But better to typedef it then to MyClassPtr or MyClass::ptr.
Still, factories they are like "new". When I want I put result of new inside of std::auto_ptr. But I don't want to be forced to call "release" all the times when I don't want smart pointer.

With C++11 you should be able to use std::unique_ptr as the other smart pointer types have constructors that take a std::unique_ptr. If you maintain an internal list of such resources then you'd probably want to use std::shared_ptr.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!