auto_ptr 陷阱和陷阱

发布于 2024-09-16 22:08:29 字数 528 浏览 11 评论 0原文

除了使用 auto_ptr 的所有已知好处之外,auto_ptr “最差做法”是什么?

  1. 创建 auto_ptrs 的 STL 容器。 auto_ptrs 不满足“CopyConstructable”要求。另请参阅 Scott Meyer 的“Effective STL”,第 8 项。

  2. 创建数组的 auto_ptrs 销毁时,auto_ptr 的析构函数使用“delete”(而不是“delete[]”)来销毁拥有的对象,因此此代码会产生未定义的行为: auto_ptr api(new int[42]);

  3. 不处理使用 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"?

  1. Creating STL contrainers of auto_ptrs.
    auto_ptrs don't fulfill the 'CopyConstructable' requirement. See also Scott Meyer's "Effective STL", item 8.

  2. 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]);

  3. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

百合的盛世恋 2024-09-23 22:08:29

不确定这是否是一个陷阱/陷阱,但它肯定不太明显:

  • const auto_ptr 无法转移其所包含指针的所有权

换句话说:

const auto_ptr<Foo> ap(new Foo());
auto_ptr<Foo> ap2;

ap2 = ap; // Not legal!

如果您想,这实际上非常有用采用 auto_ptr 参数并保证您不会获得所包含指针的所有权,但如果您期望 const auto_ptr 表现得像 Foo const *。

Not sure if this is a trap/pitfall, but it's certainly less than obvious:

  • A const auto_ptr cannot have its ownership of the contained pointer transferred

In other words:

const auto_ptr<Foo> ap(new Foo());
auto_ptr<Foo> ap2;

ap2 = ap; // Not legal!

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 a Foo const*.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文