Basically the question from the title. Consider I have to use some asynchronous API, does a reference to the local scope shared ptr in lambda preserve it's lifetime? And is this a safe practice?
class A
{
public:
static void foo();
}
A::foo()
{
std::shared_ptr<MyType> MyTypePtr = std::make_shared<MyType>();
MyTypePtr->asyncAPI([&MyTypePtr]() // this would return as soon as called
{
// doStuffWith MyTypePtr...
});
}
CodePudding user response:
This lambda captures the shared_ptr
by reference. That's what "&
" means, in the capture list. It only captures a reference to the shared_ptr
. When the function returns the shared_ptr
gets destroyed, leaving the lambda holding a bag with a reference to a destroyed object. Any further usage of this object results in undefined behavior.
A lambda capture never preserves the lifetime of anything. It either captures by value, effectively copying the captured object (with the original object's lifetime not affected in any way), or it captures by reference.
CodePudding user response:
Please don't do so!
If I understand correctly, the lambda will be executed on another thread. The suggestion still works even if it's not the case.
If you can't promise the lifetime of the shared_ptr
, pass it by value, and the lifetime of the object will be extended.
MyTypePtr
will be destroyed once it leaves the scope of A::foo()
. And the reference in the lambda will be a dangling reference.