I wan't to capture a shared_ptr by value in a lambda to ensure the lifetime of the object extends to the point the lambda function is called.
I don't actually need the shared_ptr otherwise. If I do:
shared_ptr<..> sp;
sp->async_call( [sp](){} );
Is sp guaranteed to get copied even though the body doesn't reference it?
I would say that it is guaranteed because of this quote.
5.1.2
21 When the lambda-expression is evaluated, the entities that are captured by copy are used to direct-initialize each corresponding non-static data member of the resulting closure object. (For array members, the array elements are direct-initialized in increasing subscript order.) These initializations are performed in the (unspecified) order in which the non-static data members are declared. [Note: This ensures that the destructions will occur in the reverse order of the constructions. — end note ]
EDIT: On second thought since the object is direct-initialized copy elision doesn't even come into play.Because of the criteria for copy elision in § 12.8
, too long to post, I don't believe that the copy can be elided
Something to keep in mind though, std::shared_ptr
is not thread safe for most purposes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With