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;
}
Is it such a process that foo clear all its elements and then traverse bar to construct its new elements? Or foo traverse all the keys of foo and bar and then execute only necessary modification? I encountered such a situation that access to a map by key can't work for a short time. And the reason may be that the map was being updated using the "=" assignment (foo=bar). Is it possible to solve this problem by using std::swap (foo.swap(bar))? Or a read-write lock must be used?
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?
What your doing there is a copy assign. Meaning that first the foo
will be cleared and then the elements in bar
will be copied to it.
I encountered such a situation that the access to a map by key can't work for a short time.
I'm assuming that your multithreading and that's why your having that issue. As @Jarod42 and @Some programmer dude stated, assignment or modifying a map is not thread safe, meaning that the resources must be locked prior to modifying it. You can do this using a std::mutex
.
Is it possible to solve this problem by using std::swap (foo.swap(bar))?
The specification does not say anything about it being thread safe so its best advised to make sure that the resources are locked before swapping.
Also note that your not only assigning the values from bar
to foo
when using std::map<,>::swap
or std::swap
, your also altering bar
by assigning foo
's values to it. Its not the same as foo = bar;
.
Additional: std::atomic