Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ memory management when passing shared_ptr to lambda

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.

like image 645
SundayMonday Avatar asked Feb 21 '15 05:02

SundayMonday


1 Answers

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).

like image 79
user253751 Avatar answered Sep 18 '22 16:09

user253751