简体   繁体   中英

Swapping vs. assigning with std::map [] operator (const issue)

I'm currently using the [] operator on a std::map :

map[key] = value;

Nothing too crazy. However, my value contains a const public member:

class Value
{
public:
    Value(int input) : member(input) { }
    const int member;
};

Without getting into the details of my application, the const member is something we want to keep. Given that, I was assuming that map[key] = value was doing something like first erasing the existing value, then inserting the new one:

map.erase(map.find(key));
map.insert(make_pair(key, value));

However, what actually seems to be happening is that the operator [] returns a reference to the Value, and thus tries to use the = assignment or move operator or something. Clearly, this can't work because the member can't be reassigned. Now, I'm OK with just calling erase then insert myself, but I was wondering if there was a way to pull off map[key] = value that uses this "swap" technique.

There's no easy way to implement a map like that in C++. Think about it: In order to do this you would have to make map[] return a proxy object with an overloaded assignment operator that then calls erase and remove on the underlying map, while also being careful to make sure it still behaves as a reference to its value when used as an rvalue. Returning reference is the only sensible way to do things, and is more intuitive as well.

As far as how to do what you want, you should probably just write a function to do so, and call that function instead of trying to assign elements to the map directly.

I suppose you define your map as something like:

std::map<Key, Value> mymap;

Please note that the internal node of the map stores copies of your originally passed Key and Value. If you want to use swap semantics you should use pointers to Value instead, something like:

std::map<Key, std::shared_ptr<Value> > mymap;

and then to change the value will be something like:

mymap[key].reset(new Value(...));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM