【发布时间】:2016-10-08 05:04:13
【问题描述】:
我正在尝试将一个局部变量移动到 lambda 的捕获中。
#include <thread>
#include <iostream>
// Moveable but not copyable object.
class WorkUnit
{
public:
WorkUnit(int) {}
WorkUnit(WorkUnit&&) noexcept {}
WorkUnit& operator=(WorkUnit&&) noexcept {return *this;}
WorkUnit(WorkUnit const&) = delete;
WorkUnit& operator=(WorkUnit const&) = delete;
// Non const function.
void doWork()
{
std::cerr << "Work\n";
}
};
int main()
{
WorkUnit data(4);
// Use C++14 generalized lambda capture.
std::thread test([data{std::move(data)}]()
{
// here it is complaining the `data` is a const value.
// Is there a way to capture this as a non const?
data.doWork();
}
);
test.join();
}
当我编译时,我得到了这个。
> g++ -std=c++14 WU.cpp
Test.cpp:26:13: error: member function 'doWork' not viable: 'this' argument has type 'const WorkUnit',
but function is not marked const
data.doWork();
^~~~
我希望捕获的值不是 const。
【问题讨论】:
-
把
mutable放在[data = std::move(data)]() /*here*/ {之后 -
或者通过引用捕获它:
[&data]() { data.doWork(); }。 -
@PiotrSkotnicki 为什么这里不允许使用初始化程序?
-
@PiotrSkotnicki 是否允许作为 init-capture?实际上标准中并没有提到这样的初始化,而它使用
x = std::move(x)like 语句作为示例,但我猜它是允许的。 -
现在我认为是允许的