我可以通过引用函数来传递 auto_ptr 吗?
下面的函数就OK了:
void DoSomething(auto_ptr< … >& a)....
is the following function OK:
void DoSomething(auto_ptr< … >& a)....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以做到,但我不确定你为什么要这样做。
如果您使用 auto_ptr 来指示 ptr 的所有权(正如人们通常所做的那样),那么如果您想将 ptr 的所有权转移给函数,则只需将 auto_ptr 传递给函数,在这种情况下,您将传递按值传递 auto_ptr:
因此任何调用 DoSomething 的代码都会放弃对 ptr 的所有权:
否则只需按值传递 ptr:
或将引用传递给指向的对象:
第二种通常更可取,因为它更明确地表明 DoSomething 不太可能尝试删除该对象。
You can do it but I'm not sure why you would want to do it.
If you're using the auto_ptr to indicate ownership of the ptr (as people generally do), then you only need to pass the auto_ptr to a function if you want to transfer ownership of the ptr to the function, in which case you would pass the auto_ptr by value:
So any code calling DoSomething relinquishes ownership of the ptr:
Otherwise just pass the ptr by value:
or pass a ref to the pointed to object:
The second is usually preferable as it makes it more explicit that DoSomething is unlikely to attempt to delete the object.