I'm wondering how delete [] operators work with pointers returned by a function, and not with dynamic allocation in the same scope as the delete operator. Let's say I have a trivial function like this:
int *getArray() { int *returnVal = new int[3]; returnVal[0] = returnVal[1] = returnVal[2] = 0; return returnVal; }
Now that I need to use this array in my code, I would do the following:
int *vals = getArray(); // use values... delete[] vals;
However, I wonder how the C ++ compiler knows how big the allocated block of memory was (and therefore how many memory elements need to be removed from vals )? Is this a valid method or will I need to delete each array value separately (for example, in the code below)?
int *vals = getArray(); // use values... delete vals + 2; delete vals + 1; delete vals;
source share