Is returning auto_ptr from functions wrong/error-prone?

十年热恋 提交于 2019-12-10 23:53:20

问题


Let's say I'm using std::auto_ptr in my code.*

Is there any danger in returning an std::auto_ptr object?
i.e. Could it result in a memory leak, undefined behavior, etc.? or is it a safe use of std::auto_ptr?

*I'm not asking if there is a better substitute (like shared_ptr); I'm specifically asking about the pitfalls of returning auto_ptr itself.


回答1:


In general it's safe and can lead to more robust code. It should not lead to a memory leak since the memory pointed to is automatic deleted.

But there are some cases where you have to take care:

  • Copies of auto_ptr are not equal!
  • Construction of one auto_ptr from another will release the object the first pointer was pointing to

Please see here:

  1. http://www.gotw.ca/publications/using_auto_ptr_effectively.htm
  2. http://www.cprogramming.com/tutorial/auto_ptr.html

The auto_ptr template class is designed to help manage memory in a semi-automatic way and prevent memory leaks when unexpected events such as exceptions would otherwise have caused the normal cleanup code to be skipped.

(quoted from (2))



来源:https://stackoverflow.com/questions/17400078/is-returning-auto-ptr-from-functions-wrong-error-prone

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