从函数返回auto_ptr错误/容易出错吗? [英] Is returning auto_ptr from functions wrong/error-prone?

查看:108
本文介绍了从函数返回auto_ptr错误/容易出错吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在我的代码中使用std::auto_ptr.

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

返回std::auto_ptr对象是否有危险?
即会导致内存泄漏,不确定的行为等吗?还是安全使用std::auto_ptr?

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?

*我询问是否有更好的替代品(例如shared_ptr);我特别是在问返回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.

推荐答案

通常,它是安全的,并且可以导致更健壮的代码.因为指向的内存是自动删除的,所以它不会导致内存泄漏.

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:

  • 不相等
  • 从另一个构建一个auto_ptr释放第一个指针指向的对象
  • Copies of auto_ptr are not equal!
  • Construction of one auto_ptr from another will release the object the first pointer was pointing to

请在这里查看:

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

auto_ptr模板类旨在帮助以半自动方式管理内存,并防止在异常之类的意外事件导致正常的清理代码被跳过时的内存泄漏.

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.

(引自(2))

这篇关于从函数返回auto_ptr错误/容易出错吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆