下面的程序运行没有错误。
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
class userContext {
public:
int id;
int value1;
int value2;
userContext():id(-1),value1(-1),value2(-1){}
userContext(userContext &context) {
this->id = context.id;
this->value1 = context.value1;
this->value2 = context.value2;
}
};
int main() {
userContext a;
a.id = 1;
a.value1 = 2;
a.value2 = 3;
// map<int,userContext> Map;
// Map[1] = a;
cout << a.value1 << endl;
cout << a.value2 << endl;
return 0;
}
但是如果我引入一个 map ,它会报错。为什么会这样?
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
class userContext {
public:
int id;
int value1;
int value2;
userContext():id(-1),value1(-1),value2(-1){}
userContext(userContext &context) {
this->id = context.id;
this->value1 = context.value1;
this->value2 = context.value2;
}
};
int main() {
userContext a;
a.id = 1;
a.value1 = 2;
a.value2 = 3;
map<int,userContext> Map;
Map[1] = a;
cout << Map[1].value1 << endl;
cout << Map[1].value2 << endl;
return 0;
}
部分编译错误输出:
locks.cpp:20:7: required from here
/usr/include/c++/7/bits/stl_pair.h:292:17: error: ‘constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _T2>&) [with _T1 = const int; _T2 = userContext]’ declared to take const reference, but implicit declaration would take non-const
constexpr pair(const pair&) = default;
但是,将复制构造函数签名更改为 userContext(const userContext &context)
可以解决编译错误并且程序可以正常执行。请解释。
谢谢!
最佳答案
不通过 const
引用传递复制对象的复制构造函数不满足 AllocatorAwareContainer 的要求,概念之一> 由 std::map
要求。
如果您没有在 std::map
构造中传递替代的 allocator,编译将失败。
引用:https://en.cppreference.com/w/cpp/named_req/AllocatorAwareContainer
关于c++ - 与 map 一起使用时复制构造函数常量错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53883144/