When I allocate a dynamic array in C++ (T * p = new T[n]
), I use delete [] p to free the allocated memory. Obviously, the system knows the array size (in order among other things to call n times T's destructor). This is discussed elsewhere. For instance How does delete[] “know” the size of the operand array?. This is implemenation details.
But why was it not decided to make this information available?
Thx
std::vector
. Seriously, that's what it's trying to encourage you to use. – Griffithnew
andnew[]
, then do a no-opoperator delete
andoperator delete[]
because I know I won't need that memory again. I wouldn't need to store the size of each allocation, just anext
pointer. – Payolaoperator new[]
doesn't allocate items; it allocates space for items.new X[whatever]
doesn't care how much space was actually allocated, as long as it's at least the amount that the compiler requested in the call tooperator new[]
. The compiler generates code to keep track of the number of objects that were constructed, usually in "extra" memory at the beginning of the allocated block. – RubricThe compiler generates code to keep track of the number of objects that were constructed
doesn't need to be true - it is as a rule of thumb, but it doesn't have to. In the case it doesn't, the size just isn't available. – Mouthpart