复制/移动std :: map中键/值类型的要求? [英] Copy/move requirements for the key/value types in a std::map?

查看:396
本文介绍了复制/移动std :: map中键/值类型的要求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码混淆了我:

struct foo {
  int i;

  foo(int j) : i(j) {}

  foo(const foo &) = delete;
  foo(foo &&) = delete;
  foo &operator=(const foo&) = delete;
  foo &operator=(foo&&) = delete;
};

bool operator<(const foo &f1, const foo &f2)
{
  return f1.i < f2.i;
}

int main(int argc, char **argv)
{
  std::map<foo,int> f;
  std::map<foo,int> f2 = f; //error (as expected)
  std::map<foo,int> f3 = std::move(f); //no error (why?)
  return 0;
}

因为我没有错误,对象被创建(甚至不会移动另一个键对象到它)。

Because I get no error there, it seems like when moving a map no key object is created (not even for moving another key object into it).

为什么不?我可以依据C ++ 11标准来依赖这个行为吗?

Why not? Can I rely on this behavior according to the C++11 standard?

更一般的说, std :: map

More generally, what copying/moving requirements does a std::map place on the key and value types and under what conditions?

推荐答案

>将一个地图复制分配给另一个地图需要复制每个项目。由于您无法复制项目,因此您无法复制分配地图。

Copy-assignment of one map to another requires copying each item. Since you cannot copy items, you cannot copy-assign the maps.

实际的地图对象在运行时是否为空,是无关紧要的,因为这些只是 static 注意事项,完全由对象的类型决定。

Whether the actual map object is empty at runtime is immaterial, since these are purely static considerations, determined entirely by the types of the objects.

(这就像问为什么 sin )需要一个浮点单位,当清楚的结果是一个整数。)

(It's like asking why sin(0) requires a floating point unit when clearly the result is an integer.)

另一方面,移动整个地图是好的,因为容器是基于节点的,并且没有实际值被改变,只是节点是。事实上,基于移动构建或移动分配节点的容器不需要元素可以被复制可移动

Moving the entire map, on the other hand, is fine because the container is node-based and no actual values are mutated, just the nodes are. In fact, move-constructing or move-assigning node based containers doesn't require the elements to be copyable or movable or assignable at all.

(对于以合适的方式管理动态内存的所有容器,例如通过 std :: allocator< value_type> 它对于 std :: array 当然不是真的,并且它是否会保持 std :: dynarray是有趣的,以及@Jonathan Wakely指出,如果分配方案不能移动节点批发。)

(This should be true for all containers that manage dynamic memory in a suitable fashion, such as via std::allocator<value_type>, but it would of course not be true for something like std::array, and it would be interesting whether or not it would hold for std::dynarray, and as @Jonathan Wakely noted, if the allocation scheme isn't able to move nodes wholesale.)

这篇关于复制/移动std :: map中键/值类型的要求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆