c++ - 与 map 一起使用时复制构造函数常量错误

标签 c++

下面的程序运行没有错误。

#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/

相关文章:

c++ - 具有特定于子类的模板化参数类型的 Qt SIGNAL 架构

c++ - 如何在C++中解析命令行参数?

c++ - 无法实例化标准方面

c++ - QT make app查看sourceforge.net是否有更新

c++ - 将对象实例作为函数参数传递——此代码是否调用未定义的行为?

c++ - 在模板化构造函数中调用构造函数时的有趣行为

c++ - (C++) 试图记住在哪里定义函数

c++ - 可以加载 C/C++ 和 Python 插件的应用程序

c++ - 没有名为_M_impl的成员或方法,如何使用pvector打印用clang++和libc++编译的C++的STL vector ,

c++ - 未延迟的无限 while 循环是不好的做法吗?