Reputation: 159
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?
Upvotes: 2
Views: 9994
Reputation: 13877
Objects allocated with new
must eventually be freed with delete
, or there will be leaks. Allocation with new
is independent of function calls - you can create something with new
in one function and free it with delete
in another without problems.
If you want an object that is allocated in a function and freed when the function exits, just do this:
void foo(...) {
// some code
MyClass myobj(...); // object allocated here
// some more code
return; // object freed here (or whenever function exits)
}
If you need to pass a pointer to your object to a function, you needn't use new
for that either; you can use the &
operator:
std::vector<int> myvec(pV);
foo->func(&myvec);
In this case myobj
is an automatic variable which is placed on the stack and automatically deleted when the function exits. There is no need to use new
in this case.
Upvotes: 2
Reputation: 727137
There is no such thing as new objects "expiring" in C++: it is not a garbage collected or reference counted language, so you are expected to manually code all memory management of objects that you allocated with new
or new[]
.
In this particular case, you could use unique_ptr
to ensure automated deletion:
for (int i = 0 ; i != 10000 ; i++) {
std::unique_ptr<std::vector<int> > tmp = new std::vector<int>(pV);
foo->func(tmp);
}
There is no magic here, even though it does not look like there is a delete
: the call to delete
is coded explicitly inside unique_ptr
, so for all practical purposes it's still manual.
A better solution would be to allocate your vector in the automatic storage, and pass a pointer to foo->func
:
for (int i = 0 ; i != 10000 ; i++) {
std::vector<int> tmp(pV);
foo->func(&tmp);
}
Upvotes: 7
Reputation: 13520
I think the best approach is neither.
Simply pass pV
itself. It will get copied (by the copy constructor) so a new vector will be created anyway. It will be automatically destroyed upon function return.
Upvotes: 2