Is there any reason to use auto_ptr?

守給你的承諾、 提交于 2019-11-30 22:13:55

问题


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 many auto_ptr's pitfalls.

My question is: are there any real life tasks where auto_ptr is really usefull and does fit there well?


回答1:


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.



回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/4554162/is-there-any-reason-to-use-auto-ptr

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