I've been doing some research on how C++ handles pointers passed as arguments, but haven't been able to find a solid 'yes/no' answer to my question so far.
Do I need to call delete/free on them, or is C++ smart enough to clear those on it's own?
I've never seen anyone call delete on passed pointers, so I'd assume that you don't need to, but I'd like to know if anyone knows any situations when doing it is actually required.
Thanks!
The storage used for pointers passed as arguments will be cleaned up. But the memory that they point to will not be cleaned up.
So, for instance:
void foo(int *p) // p is a copy here
{
return;
// The memory used to hold p is cleared up,
// but not the memory used to hold *p
}
int main()
{
int *p = new int;
foo(p); // A copy of p is passed to the function (but not a copy of *p)
}
You will often hear people talk about "on the heap" and "on the stack".* Local variables (e.g. arguments) are stored on the stack, which is automatically cleaned up. Data allocated using new
(or malloc
) is stored on the heap, which is not automatically cleaned up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With