[Ed.: C++11 lambdas support capturing local variables by value and by reference... but not by move. This will likely be addressed in the next standard, but in the meantime we need workarounds, usually involving a shared_ptr
, to get the right behavior. In this article, Marco Arena looks at the shared_ptr
approach and offers another potential helper. Observing the tradeoffs in these workarounds can instructive.]
Learn How to Capture by Move
by Marco Arena
what if I want to capture by moving an object instead of both copying and referencing? Consider this plausible scenario:
function<void()> CreateLambda() { vector<HugeObject> hugeObj; // ...preparation of hugeObj... auto toReturn = [hugeObj] { ...operate on hugeObj... }; return toReturn; }This fragment of code prepares a
vector
ofHugeObject
(e.g. expensive to copy) and returns a lambda which uses thisvector
(thevector
is captured by copy because it goes out of scope when the lambda is returned). Can we do better?"Yes, of course we can!" – I heard. "We can use a
shared_ptr
to reference-count the vector and avoid copying it." ...
Add a Comment
Comments are closed.