Is there any reason to use auto_ptr?

前端 未结 4 1203
一生所求
一生所求 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: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.

提交回复
热议问题