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

后端 未结 3 562
借酒劲吻你
借酒劲吻你 2021-02-02 02:37

I have a project which I would like to make more use of smart pointers. Overall, I have been successful in this goal. However, I\'ve come across one things which I\'m not sure w

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-02 02:59

    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 make_foo()
    {
        return auto_ptr(new Foo);
    }
    
    Foo *raw_pointer=make_foo().release();
    shared_ptr shared_pointer=make_foo();
    auto_ptr 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

提交回复
热议问题