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

标签 c++ templates

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

有两个模板类,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/

相关文章:

c++ - 将文本绘制到屏幕

C++ 错误 LNK2028、LNK2019 和 LNK1120。它们是什么意思,我该如何解决它们?

c++:没有匹配的函数调用,特别是它被声明为参数类型不匹配

C++ CRTP 名称查找

c++ - 为什么类模板的成员函数声明都应该是良构的?

带有正则表达式的 JavaScript 模板

c++ - 是否保证初始化顺序

c++ - 使用 isalpha() C++ 的问题

c++ - C++中的模板格式

c++ - 防止从 unique_ptr 到 shared_ptr 的赋值