在以下代码中
#include <memory>
#include <thread>
#include <utility>
void f1(std::unique_ptr<int>&& uptr) {}
void f(std::unique_ptr<int>&& uptr)
{
auto thread = std::thread([uptr{ std::move(uptr) }]() {
f1(std::move(uptr));
});
}
int main()
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
对std::movelambda内部的调用无法编译:
[x86-64 gcc 8.1 #1] error: binding reference of type'std::unique_ptr<int>&&'
to 'std::remove_reference<const> std::unique_ptr<int>&>::type'
{aka 'const std::unique_ptr<int>'} discards qualifiers
Run Code Online (Sandbox Code Playgroud)
现场演示:https://godbolt.org/g/9dQhEX
为什么会出现此错误,如何解决?哪里const来的?
lub*_*bgr 17
你需要制作lamdba,mutable因为const默认情况下闭包变量是限定的.
auto thread = std::thread([uptr{ std::move(uptr) }]() mutable {
//^^^^^^
f1(std::move(uptr)); /* Works, no constness-violation.*/
});
Run Code Online (Sandbox Code Playgroud)
您应该使 lambda 状态可变:
auto thread = std::thread([uptr{ std::move(uptr) }]() mutable
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
394 次 |
| 最近记录: |