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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With