I am trying to understand why this is not possible. Suppose I have a ctor for object Foo that accepts a lambda which returns a std::unique_ptr
for an object Bar. Using capture value, I want to save the the raw pointer of the returned std::unique_ptr
to a variable outside the lambda.
Bar* bar_ptr;
auto foo = std::make_unique<Foo>([this]()
{
auto bar = std::make_unique<Bar>();
bar_ptr = bar.get();
return bar;
})
// Assume foo is alive, has called the lambda, has ownership of bar and does not destroy it.
bar_ptr->DoSomething(); // fails
My only guess is that it is something to do with the implicit move because of return bar
. However I have other code where a std::move
is no issue like so:
auto bar = std::make_unique<Bar>();
Bar* bar_ptr = bar.get();
auto foo = std::make_unique<Foo>(std::move(bar));
bar_ptr->DoSomething() // no problem
Aucun commentaire:
Enregistrer un commentaire