在地图上原位构建不可移动的对象 [英] Construct-in-place an unmoveable object in a map
问题描述
我正在尝试在包含原子的地图中构造一个对象,因此既不能复制也不能移动AFAICT.
I'm trying to construct an object in a map that contains an atomic, so it can neither be copied nor moved AFAICT.
我对C ++ 引用的理解是,地图emplace
应该能够做到这一点.但是以下代码由于删除或不存在构造函数而无法编译.使用make_pair
没有帮助.
My reading of C++ reference is that map emplace
should be able to do this. But the following code does not compile because of deleted or non-existent constructors. Using make_pair
does not help.
#include <atomic>
#include <unordered_map>
class Z {
std::atomic<int> i;
};
std::unordered_map<int, Z> map;
void test(void) {
map.emplace(0, Z()); // error
map[0] = Z(); // error
}
这可能吗?如果不能,为什么呢?
Is this possible, and if not, why not?
在Linux上,编译器为gcc 4.8.1
Compiler is gcc 4.8.1, on Linux
推荐答案
map.emplace(std::piecewise_construct, std::make_tuple(0), std::make_tuple())
将在位置0
处构造一个零参数Z
.
map.emplace(std::piecewise_construct, std::make_tuple(0), std::make_tuple())
will construct a zero-argument Z
at location 0
.
map[0]
还没有的话,它也会这样做.
map[0]
will also do it if it is not already there.
emplace
使用参数来构造std::pair<const K, V>
. std::pair
有一个带有std::piecewise_construct_t
标签的构造函数,该构造函数带有两个元组,第一个用于构造第一个参数,第二个用于构造第二个参数.
emplace
takes the arguments to construct a std::pair<const K, V>
. std::pair
has a std::piecewise_construct_t
tagged constructor that takes two tuples, the first is used to construct the first argument, the second to construct the second argument.
因此,std::pair<const int, Z> test( std::piecewise_construct, std::make_tuple(0), std::make_tuple() )
就地构造test
元素,const int
由(0)
构造. Z
由()
构造.
so std::pair<const int, Z> test( std::piecewise_construct, std::make_tuple(0), std::make_tuple() )
constructs the test
s elements in-place, the const int
is constructed with (0)
. The Z
is constructed with ()
.
map.emplace
转发的是std::pair
构造函数的参数.
map.emplace
forwards is arguments to the std::pair
constructor.
这篇关于在地图上原位构建不可移动的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!