'auto_ptr'和STL容器:写一个错误使用的例子 [英] 'auto_ptr' and STL containers: writing an example of erroneous usage

查看:213
本文介绍了'auto_ptr'和STL容器:写一个错误使用的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读本教程后提出的这个问题:
http://www.cprogramming。 com / tutorial / auto_ptr.html

This question raised after reading this tutorial: http://www.cprogramming.com/tutorial/auto_ptr.html

您可以在其中找到以下语句:此行为的一个微妙后果是自动 _ ptrs在所有情况下都无法正常工作。例如,对标准模板库使用auto _ ptr对象可能会导致问题,因为STL中的某些函数可能会在容器(如矢量容器类)中复制对象。一个例子是排序函数,它使容器中的一些对象的副本被排序。因此,此副本可以彻底删除容器中的数据!

There you can find the following statement: A subtle consequence of this behavior is that auto_ ptrs don't work well in all scenarios. For instance, using auto _ptr objects with the standard template library can lead to problems as some functions in the STL may make copies of the objects in containers such as the vector container class. One example is the sort function, which makes copies of some of the objects in the container being sorted. As a consequence, this copy can blithely delete the data in the container!

大多数关于'auto_ptr'的论文告诉我们如下:
不要对STL容器使用'auto_ptr'它们通常在执行内部操作时复制它们的元素例如,考虑 sort on std :: vector

Most of the papers concerning 'auto_ptr' tell us something like following: "Never use 'auto_ptr' with STL containers! They often copy their elements while performing intrinsic operations. For example consider sort on std::vector".

所以我的目标是编写代码示例来说明这一点,或者证明这样的示例在理论上是真的,很奇怪的实践

PS @everybody_who_also_knows_that_auto_ptr_is_deprecated
也知道这个。但你不考虑技术原因(遗留代码或旧编译器),可能不允许新的指针容器使用?此外,这个问题是关于旧的和坏的(如果你愿意) auto_ptr

P.S. @everybody_who_also_knows_that_auto_ptr_is_deprecated I also know this. But don't you consider technical reasons (legacy code or old compiler) that may not allow new pointer containers usage? And moreover this question is about old and bad (if you'd like) auto_ptr.

推荐答案

我现在没有MSVC,但从g ++的错误判断,我想这是原因:

I don't have MSVC right now, but judging from the error from g++, I guess this is the reason:

auto_ptr< T> 只有一个复制构造函数,它接受可变引用(§D.10.1.1[auto.ptr.cons] / 2-6):

auto_ptr<T> only has a "copy constructor" which takes mutable references (§D.10.1.1[auto.ptr.cons]/2­–6):

auto_ptr(auto_ptr& a) throw();
template<class Y> auto_ptr(auto_ptr<Y>& a) throw();

但是 vector :: push_back const引用(§23.3.6.1[vector.overview] / 2)。

But vector::push_back will accept a const reference (§23.3.6.1[vector.overview]/2).

void push_back(const T& x);

所以不可能通过push_back构造一个auto_ptr,因为没有构造函数需要const引用。

So it is impossible to construct an auto_ptr via push_back because no constructor takes a const reference.

这篇关于'auto_ptr'和STL容器:写一个错误使用的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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