在 std::map 中使用 std::auto_ptr 安全吗?
我知道您必须小心使用自动指针(以及原因),尤其是使用 STL。但我不认为这有什么问题:
std::map<T1, std::auto_ptr<T2> >;
这安全吗?
我看到它如何在 std::vector
中中断,因为它必须不时复制其项目,但这对于 std::map 的值类型也是如此?
编辑:显然,无论是否安全,我都无法(技术上)填充地图,但我将保留这个问题以进行理论考虑。否则,视为关闭。
I am aware that you have to be careful with auto pointers (and why), especially with the STL. But I don't see a problem with this:
std::map<T1, std::auto_ptr<T2> >;
Is this safe?
I see how it would break in an std::vector
, because it has to copy its items from time to time, but is this also true for the value type of an std::map
?
Edit: Apparently, regardless whether it's safe, I cannot (technically) populate the map, but I'll leave the question open for theoretical considerations. Otherwise, consider it closed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不安全。从技术上讲,
std::auto_ptr
不满足 CopyConstructible 或 Assignable 的要求,因为使用auto_ptr
制作副本'复制构造函数或复制赋值运算符不等同于复制操作后的复制源。对于任何标准容器使用的任何类型都必须满足这些要求。您可能会发现,您似乎在一种特定用例的一种实现上获得了预期的行为,但如果您违反了容器的要求,您就不能指望您的代码在所有情况下都能工作。
It's not safe. Technically,
std::auto_ptr
doesn't meet the requirement of CopyConstructible or Assignable because copies made usingauto_ptr
's copy constructor or copy assignment operator aren't equivalent to the source of the copy after the copy operation. These requirements must be met for any type used with any standard container.You may find that you appear to get the behaviour you expect on one implementation for one particular use case but if you violate the requirements of the container you can't expect your code to work in all situations.
还是不安全。如果不出意外,第一次从地图中检索指针时,您将转移所有权并使其无效。
auto_ptr 的有效用例非常狭窄。我记得唯一遇到过的情况是,当一个对象想要明确表明它对您交给它的指针拥有所有权和责任时。
Still not safe. If nothing else, the first time you retrieved the pointer from the map you would transfer ownership and make it invalid.
There is an extremely narrow valid use case for auto_ptr. The only one I can remember coming across is when an object wants to make it explicitly clear that it takes ownership and responsibility for a pointer that you hand it.