C++ memory management when passing shared_ptr to lambda

c++, lambda, pass-by-value, reference-counting, shared-ptr

Solution

Your understanding is correct.

Also, if the lambda object is copied (as part of wrapping it in a `std::function<void()>` perhaps), then that will also increment the reference count (and decrement it when the copy is destroyed).

Problem

Consider the following C++ code: ``` void f(std::function<void()> func) { func(); } void g(std::shared_ptr<MyObject> myObjPtr) { myObjPtr->someMethod(); } void h(std::shared_ptr<MyObject> myObjPtr) { f([=](){ g(myObjPtr); }); } ``` Are there any memory leaks? My understanding is `myObjPtr` is copied into the lamba and has its reference count incremented. Then it's copied into `g()` where the reference count is incremented again. When `g()` is done, the `shared_ptr` has reference count decremented. Then after `func()` is executed in `f()` the `shared_ptr` has reference count decremented again. So I think this code keeps the reference count balanced (two increments and two decrements). However, I'm fairly new to `shared_ptr` and lambdas so my understanding could be incorrect.

Original source