0

I use boost::intrusive_ptr like this:

void func() {
    boost::intrusive_ptr < MyObject > obj = new MyObject();
    getStage()->addChild( obj );
}

If I understand this code right - here I get a memory leak because I don't free memory which was allocated for MyObject. How can I free it to avoid a memory leak?

JavaRunner
  • 2,455
  • 5
  • 38
  • 52
  • `intrusive_ptr` implements ref-counting for managing memory/resources. As a result, when all `intrusive_ptrs` pointing to some pointee are destroyed, the pointee is likewise destroyed/freed automatically. –  Nov 28 '15 at 02:26
  • @Ike I don't know how to destroy all pointers in intrusive_ptr? – JavaRunner Nov 28 '15 at 02:33
  • 1
    You don't -- whole point of `intrusive_ptr` is to do the memory management for you -- otherwise you might as well just use raw pointers. So it's basically a form of garbage collection (albeit using reference counting). Once all the references (`intrusive_ptrs`) are gone, the memory is freed automatically. –  Nov 28 '15 at 02:35
  • @ike "Once all the references (intrusive_ptrs) are gone" -- is there a way to manually remove all those pointers to free memory automatically? And the second question is my code have memory leak or not? :) – JavaRunner Nov 28 '15 at 02:48
  • 1
    Typically you just let the pointers go out of scope, e.g. But you can also release them. As for the code you posted, one thing I'm wondering is what you do in `addChild`. Does it copy `intrusive_ptr`? If so, you should be okay, but now `getStage()` has ownership over the memory as well. –  Nov 28 '15 at 03:02

0 Answers0