简体   繁体   English

交换与使用std :: map []运算符分配(const问题)

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

I'm currently using the [] operator on a std::map : 我目前正在std::map上使用[]运算符:

map[key] = value;

Nothing too crazy. 没什么太疯狂的。 However, my value contains a const public member: 但是,我的值包含一个const公共成员:

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. 没有深入了解我的应用程序的细节,const成员是我们想要保留的东西。 Given that, I was assuming that map[key] = value was doing something like first erasing the existing value, then inserting the new one: 鉴于此,我假设map[key] = value正在做的事情就像首先擦除现有值,然后插入新值:

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. 然而,实际上似乎发生的是operator []返回对Value的引用,因此尝试使用=赋值或移动运算符等。 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. 现在,我只是调用erase然后插入自己,但我想知道是否有办法拉出map[key] = value使用这种“交换”技术的值。

There's no easy way to implement a map like that in C++. 没有简单的方法来实现像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. 想一想:为了做到这一点,你必须让map []返回一个带有重载赋值运算符的代理对象,然后在底层映射上调用erase和remove,同时还要小心确保它仍然作为一个引用用作右值时的值。 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. 请注意,地图的内部节点存储了您最初传递的Key和Value的副本。 If you want to use swap semantics you should use pointers to Value instead, something like: 如果你想使用交换语义,你应该使用指向Value的指针,例如:

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

and then to change the value will be something like: 然后更改值将是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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