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

2024-06-24

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

有两个模板类,list map and 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;

to

using str_str_pair = xpair<string, string>;

一切正常。这是为什么?不应该value_type = xpair<string, string>?


我不知道在哪里newPair已声明,但错误消息似乎已经足够了。

为什么会失败:如果其中任一元素pair为 const,则该元素的赋值运算符本身将被删除。您无法分配给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

为什么地图有const关键类型: map容器根据键组织其元素。如果您更改了密钥,地图将无法再找到它。考虑:

std::map<std::string, int> m = { ... };
auto it = m.find(k);
it->first = "a different value";

Since a std::map例如,内部组织为红黑树,安全地更改密钥将需要重新组织节点。然而,在本例中,您直接在pair在节点中。改变key需要将这对从m,然后将其放回更改后的key.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++ - 复制赋值运算符被隐式删除 的相关文章

随机推荐