自动指针的容器

发布于 2024-09-02 13:55:20 字数 64 浏览 1 评论 0原文

我知道不应使用自动指针容器,这可能会导致问题。其真正原因是什么?是否有其他类型的“智能”指针可以在容器中安全使用?

I know containers of auto pointers should not be used and can cause problems. What is the actual reason for that? Is there any other kind of "smart" pointer which is safe to use in a container?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

眼波传意 2024-09-09 13:55:20

容器元素应该是真正可复制的; auto_ptr 不是。如果您制作副本,原件就会被修改(它会失去所有权)。 boost::shared_ptr 可以被复制,因为这两个指针随后将共享所有权。因此,它可以在STL容器中使用。

Container elements should be truly copyable; auto_ptr's are not. If you make a copy, the original is modified (it loses ownership). A boost::shared_ptr can be copied, as the two pointers will share ownership afterwards. Thus, it can be used in a STL container.

蓝眼泪 2024-09-09 13:55:20

问题出在 auto_ptr 中的复制语义。当您分配两个自动指针时,右侧将把内存所有权交给左侧。这意味着赋值签名是:auto_ptr& operator=( auto_ptr& rhs ) (请注意,RHS 中没有 const),因此在许多情况下它甚至无法编译。

还有其他可与容器一起使用的智能指针。在 TR1 中,有一个以 boost::shared_ptr 为模型的 shared_ptr (在某些编译器中,它正是刚刚复制的 boost 中的代码,并且更改了命名空间)。 Boost 还具有 boost::unique_ptr,它将在即将推出的标准中替代 auto_ptr。它使用移动语义对单一所有权进行建模,以便可以在内部使用它,而无需使用 shared_ptr 产生额外成本(在大多数情况下,成本并不明显)。

The problem is with the copy semantics in auto_ptr. When you assign an two auto pointers, the RHS will yield ownership of the memory to the LHS. This implies that the assignment signature is: auto_ptr& operator=( auto_ptr& rhs ) (note that there is no const in the RHS), so in many cases it won't even compile.

There are other smart pointers that can be used with containers. In the TR1 there is a shared_ptr modeled after boost::shared_ptr (in some compilers it is exactly the code in boost just copied and with the namespaces changed). Boost also has boost::unique_ptr that will be the replacement for auto_ptr in the upcoming standard. It models single ownership with move semantics so that it can be used inside without the extra cost of using shared_ptr (not that in most cases the cost is noticeable).

微凉徒眸意 2024-09-09 13:55:20

据我所知,auto_ptrs 在复制时会出现问题,因此不应在 STL 容器中使用。 shared_ptr 是你的选择。

As fas is i know, auto_ptrs have problems when copied, therefore should not be used in STL containers. shared_ptrs are your choice.

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