Idiomatic use of std::auto_ptr or only use shared_ptr?

前端 未结 5 1525
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 03:12

Now that shared_ptr is in tr1, what do you think should happen to the use of std::auto_ptr? They both have different use cases, but all use cases of

5条回答
  •  南旧
    南旧 (楼主)
    2021-02-04 03:53

    "Use shared_ptr everywhere" is a good default rule, and certainly a good starting point for teaching people about responsible use of smart pointers. However, it's not always the best choice.

    If you don't need shared ownership, shared_ptr is overkill: it has to allocate a separate memory block for the reference count, which can impact performance, and it is less clear documentation-wise.

    Personally, I use std::auto_ptr in many places where boost::scoped_ptr would also suffice: e.g. holding a heap-allocated object before ownership is transferred elsewhere, where the intervening operations might throw.

    C++0x will have std::unique_ptr to complement std::shared_ptr as a better alternative to std::auto_ptr. When it becomes widely available I'll start using that.

提交回复
热议问题