4 ms·
A capturing lambda is another way to leak a std::shared_ptr<> - i feel like it's an even easier way to run into this kind of footgun but i suppose it depends wh
by CraigJPerry 5y ago
A capturing lambda is another way to leak a std::shared_ptr<> - i feel like it's an even easier way to run into this kind of footgun but i suppose it depends whether you typically use lots of lambdas.
A reasonable solution in my case could be to use std::weak_ptr<> instead but that wouldn't be useful here.
- quietbritishjim 5y ago> A capturing lambda is another way to leak a std::shared_ptr<> How so? Do you mean if you do exactly what the article says when initialising the capture variables? Or something lambda specific?
- quietbritishjim 5y agoThis question was genuine curiosity so I'm a bit disappointed there was never a reply. On reflection, I suspect the parent comment was referring to creating circular dependencies using lambdas and std::function. For example, a class Inner wants allow notifying its owner when events happen, so it has a std::function member variable it uses for the callback function, and a class Outer has an instance of Inner as a member variable. But then passes as a callback: m_inner.set_callback([self=this->shared_from_this()](Param p){ self->handle_inner(p); }); Now Outer owns Inner (directly) and Inner holds a shared_ptr to Outer, so Outer will never be destroyed (and therefore neither will Inner).