当一张地图被复制到另一张现有地图时,具体发生了什么?

When a map is copied to another existing map, what happend in details?

int main ()
{
  std::map<char,int> foo,bar;

  foo['x']=100;
  foo['y']=200;
  foo['z']=300;

  bar['x']=100;
  bar['y']=2000;
  bar['zz']=400;

  foo=bar;
  return 0;
}

是不是这样一个过程,foo清空了它的所有元素,然后遍历bar构造它的新元素? 还是foo遍历foo和bar的所有key然后只执行必要的修改? 我遇到过这样一种情况,按键访问地图短时间无法使用。原因可能是使用“=”赋值 (foo=bar) 更新了地图。 是否可以使用 std::swap (foo.swap(bar)) 来解决这个问题? 还是一定要使用读写锁?

Is it such a process that foo clear all it's elements and then traverse bar to construct it's new elements? Or foo traverse all the keys of foo and bar and then execute only necessary modification?

你在那里做的是复制分配。这意味着首先 foo 将被清除,然后 bar 中的元素将被复制到它。

I encountered such a situation that the access to a map by key can't work for a short time.

我假设你是多线程的,这就是你遇到这个问题的原因。正如 @Jarod42@Some programmer dude 所述,分配或修改映射不是线程安全的,这意味着必须在修改之前锁定资源它。您可以使用 std::mutex.

Is it possible to solve this problem by using std::swap (foo.swap(bar))?

规范没有说明它是线程安全的,因此最好确保在交换之前锁定资源。

另请注意,您不仅在使用 std::map<,>::swapstd::swap 时将 bar 的值分配给 foo,还通过分配来更改 bar foo的价值观。它与 foo = bar;.

不同

附加:std::atomic