I have a question and I can't find an answer anywhere. However, there is some code I have to show:
#include "Vector2D"
class something
{
Vector2D * p_Position;
public:
something(){p_Position = new Vector2D;}
~something(){delete p_Position;}
};
int main()
{
std::list<something> Somethinglist;
Somethinglist.push_back(something());
Somethinglist.clear();
return 0;
}
So, this will lead to an assertion fail when it comes to the .clear()
function. So I tried out a few things. First of all this code completely works if I just don't put the delete p_Position
in the deconstructor. Why is that? Does the STL list .clear()
function automatically destroy dynamic Pointers? Or a rather direct question: How can I fix this code?
First of all this code completly works if i just don't put the delete p_Position in the deconstructor.
Because p_Position
won't be deallocated if you didn't put it in destructor. it causes memory leak.
Why is that. Does the STL list .clear() function automaticly destroy dynamic Pointers?
STL container keeps a copy of original object. when .clear()
, these objects will be freed and their destructors will be called.
Or a rather direct question: How can i fix this code?
Follow Rule of Three.
OR use smart pointer
#include <memory>
class something
{
std::unique_ptr<Vector2D> p_Position;
public:
something(){}
~something(){}
};
OR use it without pointer
class something
{
Vector2D p_Position;
public:
something(){}
};