简体   繁体   English

为什么unordered_map的pieceplace_construct参数的位置需要默认构造函数?

[英]Why does unordered_map's emplace with piecewise_construct argument needs default constructor?

I have an unordered_map which stores <string, A> pairs. 我有一个unordered_map ,它存储<string, A>对。 I wanted to emplace pairs with this snippet: 我想在这个代码段中加入配对:

        map.emplace(std::piecewise_construct,
            std::forward_as_tuple(name),
            std::forward_as_tuple(constructorArg1, constructorArg1, constructorArg1));

But if my A class doesn't have a default constructor then it fails to compile with this error: 但是,如果我的A类没有默认的构造函数,那么它将无法编译并显示以下错误:

'A::A': no appropriate default constructor available 'A :: A':没有合适的默认构造函数

C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\include\\tuple 1180 C:\\ Program Files(x86)\\ Microsoft Visual Studio 14.0 \\ VC \\ include \\ tuple 1180

Why does it need a default constructor and how can I avoid the use of it? 为什么它需要一个默认的构造函数,如何避免使用它?

std::unordered_map needs default constructor is because of operator[] . std::unordered_map需要默认构造函数是因为operator[] map[key] will construct new element using default constructor if key is not exist in map . 如果map不存在key map[key]将使用默认构造函数构造新元素。

You can totally use map without default constructor. 您可以完全使用map而无需默认构造函数。 Eg following program will compile with no error. 例如下面的程序将编译没有错误。

struct A {
    int x;
    A(int x) : x(x) {}
}; 

...

std::unordered_map<int, A> b;

b.emplace(std::piecewise_construct,
    std::forward_as_tuple(1),
    std::forward_as_tuple(2));
b.at(1).x = 2;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 带有默认构造函数的 unordered_map emplace - unordered_map emplace with default constructor 用于boost :: container :: map :: emplace()的piecewise_construct在哪里? - Where is piecewise_construct for boost::container::map::emplace()? 为什么我们在 C++20 中需要 map emplace 中的分段构造? - Why do we need piecewise_construct in map emplace in C++20? 为什么我需要在 map::emplace 中为不可复制对象的单个 arg 构造函数使用piecewise_construct? - why do i need to use piecewise_construct in map::emplace for single arg constructors of noncopyable objects? 具有显式构造函数的类是否需要emplace中的piecewise_construct? - Do classes with explicit constructors require piecewise_construct in emplace? std :: unordered_map :: emplace行为,没有移动/复制构造函数 - std::unordered_map::emplace behavior with no move/copy constructor 私有/删除拷贝构造函数的std :: unordered_map :: emplace问题 - std::unordered_map::emplace issue with private/deleted copy constructor 在unordered_map位置中使用向量构造器时,为什么只使用参数的最后一个值? - Why a vector constructor takes only last value of the parameter when using in unordered_map emplace? 使用unordered_map分配器的非默认构造函数 - Using unordered_map allocator's not default constructor 为什么使用unordered_map和tuple需要默认构造函数? - Why a default constructor is needed using unordered_map and tuple?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM