C++ std::auto_ptr 复制构造函数
std::auto_ptr 缺少 const 复制构造函数,因此我无法直接在集合中使用它。有没有办法在不使用 boost 指针集合模板的情况下获得例如 std::auto_ptr 向量?
std::auto_ptr lacks const copy constructor, therefore I cannot use it directly in collections. is there some way to have for example vector of std::auto_ptr without using boost pointer collection template?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您有 C++0x 编译器,则可以根据需要使用
shared_ptr
或unique_ptr
。此处有一个正确使用
unique_ptr
的好例子@詹姆斯·麦克内利斯。如需shared_ptr
演练,请查看此处,由 @D 提供.肖利。 [我相信,在这些线程上仍然会受到赞赏。]auto_ptr
的vector
始终无效,尽管 Visual C++ v6 不同意。If you have a C++0x compiler you can use
shared_ptr
orunique_ptr
as appropriate.There is a good example of correct
unique_ptr
usage here courtesy of @James McNellis. For ashared_ptr
walkthrough look here, courtesy of @D.Shawley. [Upvotes would still be appreciated on those threads, I am sure.]vector
ofauto_ptr
is always invalid, although Visual C++ v6 disagreed.不,你只是不能拥有 std::auto_ptr 向量,尽管有很多猜测可以。但是,如果您的编译器支持 C++0x,则可以使用 std::unique_ptr,这是已弃用的自动指针的新替代方案,引用新标准,它提供了更好的替代方案。另请参阅此帖子
No, you just can't have a vector of
std::auto_ptr
, though there exist many speculations that you can. But if your compiler supports C++0x, you can usestd::unique_ptr
, which is the new alternative of the deprecated auto pointer which, quote from the new standard, provides a superior alternative. See also this threadauto_ptr 设计用于当变量离开作用域时自动删除。你不想在集合中使用它,而是如上所述,你想使用像shared_ptr这样的东西。
auto_ptr 的典型用途示例:
如果您不确定 auto_ptr 的特殊语义,超出此用途的任何内容都可能存在危险和/或损坏。 (编辑:根据阿门的评论进行澄清)
auto_ptr is designed for auto deletion when a variable leaves scope. You don't want to use it in a collection, instead as mentioned above you want to use something like shared_ptr.
Example of auto_ptr's typical use:
Anything beyond this use is potentially dangerous and/or broken if you are not sure of the special semantics of auto_ptr. (Edit: clarify based on Armen's comment)