Is there any reason to use auto_ptr?

前端 未结 4 1157
一生所求
一生所求 2021-01-08 00:24

After reading Jossutis\' explanation on auto_ptr from his STL book I\'ve got a strong impression that whatever task I would try to use it in I\'d 100% fail becuase of one of

相关标签:
4条回答
  • 2021-01-08 00:42

    I would say it can be used, but it is not the best option.

    First, it is a matter of year or less and auto_ptr is officially deprecated. Second, there is a superior alternative: unique_ptr. Dr. Stroustrup once said about unique_ptr:

    “What auto_ptr should have been” (but that we couldn't write in C++98)

    So unless you don't have the choice, auto_ptr is not a good choice. Mainly, because most C++ compilers these days implement move semantics and provide unique_ptr.

    0 讨论(0)
  • 2021-01-08 00:43

    I use std::auto_ptr moderately often, to ensure exception safety. That is, to prevent a memory leak in the event of part of a method throwing an exception.

    For example:

    Foo &Container::addFoo(
       const std::string &name
       )
    {
      // The post conditions of the method require that the new Foo
      // has been added to this container, but the addition method
      // may throw exceptiona
      std::auto_ptr< Foo > foo(new Foo(name));
    
      foo->twiddle();// may throw
      this->addFoo(*foo);// record reference. May throw
    
      return *foo.release();
    }
    

    Edited: clarified that this->addFoo(*foo) records a reference.

    0 讨论(0)
  • 2021-01-08 00:45

    Clearly, auto_ptr looses against unique_ptr.

    Now, in a 'strict C++03 without boost' world, I use auto_ptr quite often, most notably :

    • For 'factory member functions' which return a dynamically allocated instance of a given type : I like the fact that using std::auto_ptr in the return type explicits that the object must be deleted
    • In functions which allocate an object before attempting to insert it in a container afterwards : for example in order to release() only if std::map<>::insert returns that insertion succeeded
    • In a thread procedure which pops elements from a message queue, I like storing the pop'ed element in a const std::auto_ptr to make it clear that the message will be destroyed no matter what.
    0 讨论(0)
  • 2021-01-08 00:58

    In simple scenarios when you need to temporarily control a heap-allocated object auto_ptr can be used without problems. For example if you need to conditionally create an object that will be used only within one function you can't allocate it on stack and auto_ptr lets you not care of the object lifetime should an exception occur.

    0 讨论(0)
提交回复
热议问题