以下程序正常运行。
#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;
}
但是,如果我引入地图,则会出现错误。为什么会这样?
#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)
可解决编译错误,并且程序可以正常执行。请解释。
谢谢!
答案 0 :(得分:4)
未通过const
引用传递复制的对象的副本构造函数不满足 AllocatorAwareContainer 的要求,该 AllocatorAwareContainer 是std::map
。
如果您没有在std::map
结构上传递替代的 allocator ,则编译将失败。