在lambda表达式中使用std :: atomic

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

我想在lambda表达式中捕获std::atomic。原子变量的生存期必须与lambda绑定,因此无法通过引用捕获,但是我想避免堆分配。

我如何修改以下代码片段以使其按预期方式编译和运行?

#include <atomic>

int main()
{
    std::atomic_int a{42};
    auto check = [a] () mutable { return a.fetch_sub(1) == 1; };
    //            ^ error: call to deleted constructor of 'std::atomic_int'
}
c++ lambda c++17 atomic
1个回答
0
投票

您可以直接初始化捕获并依靠C ++ 17保证的复制/移动省略:

#include <atomic>

int main()
{
    auto check = [a = std::atomic_int(42)]() mutable {
        return a.fetch_sub(1) == 1;
    };
}
© www.soinside.com 2019 - 2024. All rights reserved.