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?
any_list.clear()
doesn't delete the object? It sounds like the heap corruption is being reported due to a double delete, when the unique_ptr's destructor is called. Try setting a breakpoint ni the destructor for CMyInterfaceObject
mark 2012-04-04 08:04
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