Search code examples
c++scopec++11unique-ptr

heap corruption when leaving scope with unique_ptr


I face a problem similar to void pointer returned from function heap corruption

The similarity is that I get "Heap corruption" message when leaving the scope where unique_ptr is used.

Here the code:

void CMyClass::SomeMethod ()
{
  std::unique_ptr<IMyInterface> spMyInterface;
  spMyInterface.reset(new CMyInterfaceObject()); // CMyInterfaceObject is derived from IMyInterface

  any_list.push_back(spMyInterface.get()); // any_list: std::list<IMyInterface*>

  any_list.clear(); // only clears the pointers, but doesn't delete it

  // when leaving the scope, unique_ptr deletes the allocated objects... -> heap corruption
}

Any idea why this happens?


Solution

  • std::unique_ptr is a smart pointer that retains sole ownership of an object through a pointer and destroys that object when the unique_ptr goes out of scope.

    In your case, you have declared std::unique_ptr<IMyInterface> spMyInterface; inside of SomeMethod() so as soon as the execution leaves the scope of SomeMethod() your object gets destroyed.

    Take a look at unique_ptr