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 myObjPtrcopied to lamba and the reference count is increasing. Then it is copied to g(), where the reference count is incremented again. When g()executed, shared_ptrhas a reference count reduced. Then, after func()being executed, the f()value shared_ptragain has a reference count. Therefore, I believe that this code maintains a balance of links (two increments and two abbreviations). However, I'm pretty new to shared_ptrlambdas, so my understanding may be wrong.

+4
1

.

, ( std::function<void()> ), ( , ).

+4

All Articles