How does C ++ handle flushing pointers passed as arguments?

I am doing some research on how C ++ treats pointers as arguments, but so far I have not been able to find a reliable yes / no answer to my question.

Do I need to call delete / free on them or is C ++ smart enough to clean them myself?

I have never seen anyone call delete on passed pointers, so I would suggest that you do not need this, but I would like to know if anyone knows of any situations when this is really necessary.

Thanks!

+4
source share
5 answers

The storage used for pointers passed as arguments will be cleared. But the memory they point to will not be cleared.

So for example:

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 often hear people talking about "on the heap" and "on the stack." * Local variables (e.g. arguments) are stored on the stack, which is automatically cleared. Data allocated using new (or malloc ) is stored on the heap, which is not automatically cleared.


* However, the C ++ standard does not talk about the "stack" and the "heap" (in fact, these are implementation-specific details). It uses the terminology "automatic storage" and "distributed storage" respectively. Sub>
+9
source

The arguments passed to the method are stored on the stack, so they are automatically destroyed when the function returns - as local variables. The memory they point to is not automatically free.

+4
source

If you receive a pointer from your caller, he must release this pointer, unless otherwise indicated.

+2
source

Pointers will be copied - accepted "by value". When a function exists, they will be destroyed, but since their destructors are trivial, nothing will be done for the memory they point to.

+1
source

The pointers themselves are not. They go when the frame of the parameter stack is deleted when the function returns, like the int or char parameters. Do you need to do anything with the specified data between you and your code.

+1
source

Source: https://habr.com/ru/post/1388018/


All Articles