I’ve been toying with c++ for a little while, and coming from java one of the most confusing aspects for me is memory management. For example, lets say I have a method, and in that method I declare a pointer to an object, i want to set that pointer to an attribute of another object using a get method:
SubObject *mySubObject = anotherObject.getSubObject();
My question is, what happens to this pointer when the method ends? should i use the following before it ends?
delete mySubObject;
What if i don’t delete it? Does it remain until the entire program ends?
I’ve tried googling around for basic memory management tutorials for c++, but i typically find more advanced stuff thats way over my head, any referals would be appretiated.
Tracking memory management can be a burden, the best advice is to avoid it in as much as possible and make it explicit by avoiding raw pointers. If you only need temporary access to a variable that is held somewhere else (in your example, it is a member of a different object, and thus managed there) you should not
deleteit, and it will be better if you just hold areferencerather than a pointer, as references make explicit the fact that you are not managing that resource.