My question is what happens to the object allocated with the new operator that is inside a function call.
A specific example: I have a private vector pV which I want to send to a object/function outside of the class, foo->func(std::vector<int> *vec). I first tried to write
foo->func( new std::vector<int>(pV) )
but this resulted in a memory leak (when said function is called repeatedly inside a loop). When I specifically created a new object, called the function and then deleted that object, the whole thing worked, without the memory leak.
Shouldn’t the newly created object ‘expire’ and be deleted when the function returns? If not, how should I delete the object, from inside the called function? And which is the better approach?
Objects allocated with
newmust eventually be freed withdelete, or there will be leaks. Allocation withnewis independent of function calls – you can create something withnewin one function and free it withdeletein another without problems.If you want an object that is allocated in a function and freed when the function exits, just do this:
If you need to pass a pointer to your object to a function, you needn’t use
newfor that either; you can use the&operator:In this case
myobjis an automatic variable which is placed on the stack and automatically deleted when the function exits. There is no need to usenewin this case.