c++ - 非法使用已删除的函数

标签 c++ c++11 c++14 deleted-functions

我有一个A类

struct A
{
    A() = delete;
    A(const A&) = default;
    A& operator=(const A&) = default;
    A(A&&) = default;
    A& operator=(A&&) = default;

    explicit A(int i) ....
    // a few explicit constructors
}

当我尝试获取存储在 unordered_map 中的 strcut A 时,如下所示:

auto a = my_map[key_];

我明白了

illegal use of deleted method

错误。 我的理解是这是一个复制构造,但我不知道为什么编译器会在赋值之前调用默认构造函数。

最佳答案

来自 http://en.cppreference.com/w/cpp/container/map/operator_at :

mapped_type must meet the requirements of CopyConstructible and DefaultConstructible.

由于删除了默认构造函数,编译器正确地报告了错误。

在链接页面的下方:

Return value

Reference to the mapped value of the new element if no element with key key existed. Otherwise a reference to the mapped value of the existing element whose key is equivalent to key.

如果不存在具有给定键的元素,该函数将插入一个新元素。需要默认构造函数才能插入新元素。

关于c++ - 非法使用已删除的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49286205/

相关文章:

c++ - 无法解析类型 'std::default_random_engine'

c++ - vector <pair<int,int>>v(size);打印时显示 0 作为值

c++ - 为什么 map 上的 std::for_each 会调用复制构造函数?

c++ - 如何将大小为 64 的字节数组转换为 Arduino C++ 中的 double 值列表?

java - C++ 迭代器模型与 Java 迭代器模型

c++ - 验证 native 的 Active Directory 域信任关系

c++ - 一个人如何降低 std::shared_ptr?

c++ - 可变参数模板上的变换算法

c++ - 多位后缀表达式

c++ - 哈夫曼压缩器/解压器