Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I capture by value and don't use it will I still get a copy?

Tags:

c++

c++11

lambda

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?

like image 548
Michael Marcin Avatar asked Nov 12 '13 05:11

Michael Marcin


1 Answers

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.

like image 87
aaronman Avatar answered Oct 17 '22 17:10

aaronman