Capture and move a unique_ptr in a c++14 lambda expression

后端 未结 3 906
夕颜
夕颜 2021-02-01 01:44

I am capturing a unique_ptr in a lambda expression this way:

auto str = make_unique(\"my string\");
auto lambda = [ capturedStr = std::move(str)          


        
3条回答
  •  长发绾君心
    2021-02-01 02:44

    The operator () of a lambda is const by default, and you can't move from a const object.

    Declare it mutable if you want to modify the captured variables.

    auto lambda = [ capturedStr = std::move(str) ] () mutable {
    //                                             ^^^^^^^^^^
        cout << *capturedStr.get() << endl;
        auto str2 = std::move(capturedStr);
    };
    

提交回复
热议问题