初始化C++捕获移动是常量
C++ capture move initialized is const?
我正在尝试将局部变量移动到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 << "Workn";
}
};
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();
^~~~
我期望捕获的值为无常量。
您可以使用可变:
可变 - 允许主体修改 copy 捕获的参数,并调用其非常量成员函数
除非在 lambda 表达式中使用了关键字
mutable
,否则 函数调用运算符是常量限定的,并且对象 通过副本捕获是不可在此operator()
内部修改的。
std::thread test([data{std::move(data)}]() mutable
{
// the function-call operator is not const-qualified;
// then data is modifiable now
data.doWork();
}
);
值得注意的是,这允许对复制捕获的对象进行修改,这与原始对象无关。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 移动类的成员作为常量引用参数传递
- 我应该使我的局部变量常量还是可移动的
- 给定一个右值,为什么移动ctor比常量复制ctor更匹配
- 移动具有常量成员的类的构造和分配
- 为什么在这种情况下调用非常量右值移动构造函数?
- 初始化C++捕获移动是常量
- 移动具有常量数据成员或引用成员的类的ctor
- 移动语义和常量引用
- 外部C结构的C++默认复制/移动赋值运算符不是常量
- C++ 移动构造函数和常量成员指针或常量成员,如何对它们进行 NULIZE 以避免内存泄漏
- 移动构造函数和非常量复制构造函数
- C++,常量引用实际上比移动更快
- C++11编译器何时会使RVO和NRVO优于移动语义和常量引用绑定