在地图上原位构建不可移动的对象 [英] Construct-in-place an unmoveable object in a map

查看:66
本文介绍了在地图上原位构建不可移动的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在包含原子的地图中构造一个对象,因此既不能复制也不能移动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 tests 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆