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
305 views
in Technique[技术] by (71.8m points)

c++ - Moving unique_ptr constructed at lambda capture site into a vector fails

Dummy code of what I was trying to do:

auto test_foo = [foo_o1 = make_unique<Foo>(), &vectorOfFoo]() {
    auto foo_o2 = make_unique<Foo>();
    vectorOfFoo.push_back(std::move(foo_o2)); //COMPILES
    vectorOfFoo.push_back(std::move(foo_o1)); //ERROR: use of deleted function unique_ptr(const std::unique_ptr<_Tp, _Dp>&)
};
question from:https://stackoverflow.com/questions/65895095/moving-unique-ptr-constructed-at-lambda-capture-site-into-a-vector-fails

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

1 Answer

0 votes
by (71.8m points)

The function-call operator of the lambda is const-qualified by default, so foo_o1 that was copy-captured is non-modifiable inside of it.

You can mark the lambda as mutable:

mutable: allows body to modify the objects captured by copy, and to call their non-const member functions

E.g.

auto test_foo = [foo_o1 = make_unique<Foo>(), &vectorOfFoo]() mutable {
    auto foo_o2 = make_unique<Foo>();
    vectorOfFoo.push_back(std::move(foo_o2)); //COMPILES
    vectorOfFoo.push_back(std::move(foo_o1)); //COMPILES
};

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

...