不能std ::从lambda捕获到lambda内的函数调用,为什么?

Vio*_*ffe 8 c++ c++14

在以下代码中

#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)

  • 'const`-ness是默认的少数几个地方之一.我希望它更多. (3认同)

use*_*670 5

您应该使 lambda 状态可变:

auto thread = std::thread([uptr{ std::move(uptr) }]() mutable
Run Code Online (Sandbox Code Playgroud)