As a sequel of my previous question, I would like to ask what I am doing wrong in the following code.
The code is, for example
void myclass1::myfun()
{
myclass2* newVar = new myclass2();
/* other code and stuff */
myvector.push_back(newVar); // myvector is a member of myclass1 and is a std::vector<myclass2*>
delete newVar;
}
but when I run it, myvector returns empty, unless I comment out the delete line.
What am I doing wrong?
As already said, you cannot access or change memory when you have freed it already. You must take care of deleting your object in your destructor (or an extra function). Here’s a snippet that would do that: