我正在尝试在以下情况下使用复制分配。
有两个模板类,list map
和 xpair
.
template <typename Key, typename Value, class Less=xless<Key>>
class listmap {
public:
using key_type = Key;
using mapped_type = Value;
using value_type = xpair<const key_type, mapped_type>; //value_type
...
}
template <typename First, typename Second>
struct xpair {
First first{};
Second second{};
xpair(){}
xpair (const First& first, const Second& second):
first(first), second(second) {}
};
在main.cpp中,我试着写,
using commend = string;
using str_str_map = listmap<string,string>;
using str_str_pair = str_str_map::value_type; //value_type, to be replaced
using commend_pair = xpair<commend, str_str_pair>;
int main(...) {
commend_pair cmd_pair;
str_str_pair newPair ("Key", "value");
cmd_pair.second = newPair;
...
}
它给我一个错误提示
object of type 'xpair<const std::__1::basic_string<char>,
std::__1::basic_string<char> >' cannot be assigned because its copy
assignment operator is implicitly deleted
如果我更换
using str_str_pair = str_str_map::value_type;
到
using str_str_pair = xpair<string, string>;
一切正常。这是为什么?不应该value_type = xpair<string, string>
?
最佳答案
我没看到哪里newPair
已声明,但错误消息似乎足够了。
为什么会失败: 如果 pair
中的任一元素是常量,该元素的赋值运算符本身被删除。您无法分配给 const string
但这正是您在分配给 pair<const string, T>
时要求它执行的操作.为了简化例子
std::pair<const int, int> p(0, 0);
p.first = 1; // no, can't assign to p.first
p = std::pair<const int, int>(1, 2); // no, requires assigning to p.first
为什么 map 有 const
key 类型:map
容器根据键组织它们的元素。如果您更改了 key , map 将无法再找到它。考虑:
std::map<string, int> m = { ... };
auto it = m.find(k);
it->first = "a different value";
自 std::map
例如,在内部组织为红黑树,安全地更改 key 将需要重新组织节点。然而,在本例中,您直接在 pair
上操作在节点中。更改 key
需要从 m
中删除这对,然后将其放回原处并更改 key
.
关于C++ - 复制赋值运算符被隐式删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35299985/