如何创建包含std :: atomic的std ::对?

问题描述 投票:6回答:1

我无法弄清楚如何创建以下内容:

std::pair<std::atomic<bool>, int>

我总是得到

/usr/include/c++/5.5.0/bits/stl_pair.h:139:45:错误:使用已删除的函数'std :: atomic :: atomic(const std :: atomic&)' :first(__ x),second(std :: forward <_U2>(__ y)){}

我试过了

std::pair<std::atomic<bool>, int> pair = std::make_pair(true, 1); //doesn't work
std::pair<std::atomic<bool>, int> pair = std::make_pair({true}, 1); //doesn't work
std::pair<std::atomic<bool>, int> pair = std::make_pair(std::atomic<bool>(true), 1); //doesn't work
std::pair<std::atomic<bool>, int> pair = std::make_pair(std::move(std::atomic<bool>(true)), 1); //doesn't work

我知道std :: atomic是不可复制的,那么你应该如何在一对中创建它?这是不可能的吗?

c++ std atomic std-pair stdatomic
1个回答
7
投票

你可以做:

std::pair<std::atomic<bool>, int> p(true, 1);

这使用true初始化原子第一个成员,没有任何无关的副本或移动。在C ++ 17中,保证复制省略也允许你写:

auto p = std::pair<std::atomic<bool>, int>(true, 1);
© www.soinside.com 2019 - 2024. All rights reserved.