Heap when leaving area with unique_ptr
I am facing an issue similar to void pointer returning from function heap corruption
The similarity is that I get Heap Corruption when I go out of scope for unique_ptr.
Here's 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 is happening?
+3
source to share
1 answer
std :: unique_ptr is a smart pointer that retains ownership of an object through the pointer and destroys that object when unique_ptr goes out of scope.
In your case, you declared std::unique_ptr<IMyInterface> spMyInterface;
inside SomeMethod (), and as soon as the execution leaves the scope of SomeMethod (), your object will be destroyed.
Take a look at unique_ptr
+3
source to share