auto_ptr 陷阱和陷阱
除了使用 auto_ptr 的所有已知好处之外,auto_ptr “最差做法”是什么?
创建 auto_ptrs 的 STL 容器。 auto_ptrs 不满足“CopyConstructable”要求。另请参阅 Scott Meyer 的“Effective STL”,第 8 项。
创建数组的 auto_ptrs 销毁时,auto_ptr 的析构函数使用“delete”(而不是“delete[]”)来销毁拥有的对象,因此此代码会产生未定义的行为: auto_ptr api(new int[42]);
不处理使用 auto_ptr 成员的类中的 copy-ctor 和 op=。 人们可能天真地认为,通过使用 auto_ptr 成员,不需要为类实现复制构造函数/赋值运算符。然而,即使是单个 auto_ptr 成员也会“毒害”一个类(即违反“CopyConstructable”和“Assignable”要求)。此类类的对象在复制/赋值操作期间会部分损坏。
还有更多 auto_ptr 陷阱吗?
Besides all the known benefits of using auto_ptrs, what are auto_ptr "worst-practices"?
Creating STL contrainers of auto_ptrs.
auto_ptrs don't fulfill the 'CopyConstructable' requirement. See also Scott Meyer's "Effective STL", item 8.Creating auto_ptrs of arrays
Upon destruction, auto_ptr's destructor uses 'delete' (and never 'delete[]') to destroy the owned object, so this code yields undefined behavior:
auto_ptr api(new int[42]);Not taking care of copy-ctor and op= in a class using auto_ptr members.
One might naively think that by using auto_ptr members one doesn't need to implement the copy constructor/assignment operator for a class. However, even a single auto_ptr member 'poisons' a class (i. e. violates the 'CopyConstructable' and 'Assignable' requirements). Objects of such classes would be partly damaged during the copy/assignment operation.
Are there even more auto_ptr pitfalls?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定这是否是一个陷阱/陷阱,但它肯定不太明显:
换句话说:
如果您想,这实际上非常有用采用 auto_ptr 参数并保证您不会获得所包含指针的所有权,但如果您期望
const auto_ptr
表现得像Foo const *。
Not sure if this is a trap/pitfall, but it's certainly less than obvious:
In other words:
This is in fact quite useful if you want to take an auto_ptr argument and guarantee that you won't be taking ownership of the contained pointer, but it can also be surprising if you expect a
const auto_ptr<Foo>
to behave like aFoo const*
.