【问题标题】:copy constructor const error while using with map与 map 一起使用时复制构造函数 const 错误
【发布时间】:2019-05-21 19:54:02
【问题描述】:

以下程序可以正常运行。

#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 &amp;context) 可以解决编译错误并且程序可以正常执行。请解释一下。

谢谢!

【问题讨论】:

  • #include &lt;bits/stdc++.h&gt;Don't do this。您的程序在我要测试的平台上无法编译。
  • 此外,您的复制构造函数有一个缺陷,它无法复制id 成员。所以现在你生成了伪造的副本。
  • 您的问题类似于Why C++ copy constructor must use const object?,但您的问题的答案是删除您的复制构造函数实现并让编译器为您生成默认的。
  • @Debashish 请解释一下。这可能会有所帮助:stackoverflow.com/a/43607151/580083
  • @MatthieuBrucher 同意,但最好解释一下为什么std::map 需要它的映射类型来需要这样一个标准复制构造函数(编辑:Bathsheba 只是在他的回答)。

标签: c++


【解决方案1】:

不通过const 引用传递复制对象的复制构造函数不满足AllocatorAwareContainer 的要求,这是@ 要求的概念 之一987654323@.

如果您没有在std::map 构造中传递替代分配器,编译将失败。

参考:https://en.cppreference.com/w/cpp/named_req/AllocatorAwareContainer

【讨论】:

  • 谢谢!。一个QS。如果我在复制构造函数的开头放置了一个cout &lt;&lt;"hello"&lt;&lt;endl; 语句,那么为什么它没有被打印出来?我错过了什么吗?
  • @Debashish 也许没有调用复制构造函数。允许编译器省略复制构造函数。
  • 现在很混乱。地图需要用户定义的复制构造函数中的const 参数,它甚至没有调用它。
  • 代码需要语法正确。优化代码是一个不同的问题之后编译器认为你的代码是正确的。
猜你喜欢
  • 1970-01-01
  • 2013-08-07
  • 1970-01-01
  • 2014-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多