I just wanted to know how one would go about, or if there is even a need to, delete [] an array declared like this:
int* arrgen(int x)
{
int *newarray = new int[x];
return newarray;
}
How would you go about deleting the newarray after the function returns? Or does it "auto" delete after the function returns along with the rest of the variable native to the function?
No, you would have to delete from outside the function in this case. Anyway, if you deleted from inside the function, you would have a dangling pointer when returning, so it makes no sense.
If you want automatic deallocation, do this, making use of c++11:
std::unique_ptr<int []> newarray(new int[x]);
return newarray;
This will return newarray and when you stop using it, it will call delete [] through the unique_ptr destructor.
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