gpt4 book ai didi

C++ - 复制赋值运算符被隐式删除

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:01:29 25 4
gpt4 key购买 nike

我正在尝试在以下情况下使用复制分配。

有两个模板类,list mapxpair .

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com