Do you mean if we create a pointer using new, it remains even out of its scope? |
When you allocate memory dynamically (i.e. using
new
), that memory remains allocated until you delete it, using the
delete
keyword.
To access that memory, you need to store its address in a pointer variable. As long as you have that value, you can access the memory. The scoping rules for that pointer variable are the same as the rules for any other variable.
Note that, if the pointer variable drops out of scope, that doesn't mean the memory gets freed up; it remains allocated unless you manually delete it. We call this a
memory leak, because it causes your program to use up memory that never gets freed (until the program exits), meaning that memory can't be re-used.
In modern C++, we get around this problem by using
smart pointers, which are template classes that wrap a pointer, and which automatically free up memory at the appropriate point.
And is it correct that arrays don't remain out of scope and we should make them static to use in out of scope? |
Arrays have the same scoping rules as any other variables. If you create a local variable (be it an array, or any other kind of variable), then when it goes out of scope, the memory is reclaimed by the program and can be used to store other data.
The issue here is that, when you return an array, what you're actually returning is a pointer to the memory storing that array. If the array is local, then once it's out of scope, the pointer is pointing to memory that has been reclaimed and could have been used for something else; you can no longer rely on it containing the values you stored in it when it was being used for the array.
A static variable persists after the function has exited, so that the next time the function is called, it still holds the value it held at the end of the previous call. A side-effect of this is that the pointer you're returning to the function points to memory that still holds the values you want to access.
As Moschops says, it's not the best way to achieve what you're trying to do, but it works, and hopefully will help you understand how these language features work.