Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
885 views
in Technique[技术] by (71.8m points)

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

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

auto str = make_unique<string>("my string");
auto lambda = [ capturedStr = std::move(str) ] {
   cout << *capturedStr.get() << endl;
};
lambda();

It works great until I try to move capturedStr to another unique_ptr. For instance, the following is not working:

auto str = make_unique<string>("my string");
auto lambda = [ capturedStr = std::move(str) ] {
    cout << *capturedStr.get() << endl;
    auto str2 = std::move(capturedStr); // <--- Not working, why?
};
lambda();

Here is the output from the compiler:

.../test/main.cpp:11:14: error: call to implicitly-deleted copy
constructor of 'std::__1::unique_ptr<std::__1::basic_string<char>,
std::__1::default_delete<std::__1::basic_string<char> > >'
        auto str2 = std::move(capturedStr);
             ^      ~~~~~~~~~~~~~~~~~~~~~~ ../include/c++/v1/memory:2510:31: note: copy constructor is implicitly
deleted because 'unique_ptr<std::__1::basic_string<char>,
std::__1::default_delete<std::__1::basic_string<char> > >' has a
user-declared move constructor
    _LIBCPP_INLINE_VISIBILITY unique_ptr(unique_ptr&& __u) _NOEXCEPT
                              ^ 1 error generated.

Why isn't it possible to move capturedStr?

question from:https://stackoverflow.com/questions/27800468/capture-and-move-a-unique-ptr-in-a-c14-lambda-expression

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...