Item 37. Array Allocation
When you allocate memory, use DELETE when you release it; use New [] when allocating [], then releases DELETE []. T * at = new t; // Non-arrayt * aryt = new t [12]; // arraydelete [] aryt; // arraydelete at; // non-array
-------------------------------------------------- --1, why? Why do you need to use it? When allocating an array and non-array, the operator used is different, and the corresponding release operation is different. void * operator new (size_t) throw (bad_alloc); // operator newvoid * operator new [] (size_t) throw (bad_alloc); // array newvoid operator delete (void *) throw (); // operator deletevoid operator delete [ ] (void *) throw (); // array delete
2, when a class only writes new and delete, when arranging this class, the assignment and release operation function is two globally :: operator new [] and :: operator delete []. Therefore, in order to ensure the consistency of allocation behavior, it is a good choice to declare an array and non-array allocation. Class Handle {public: // ... void * operator new (size_t); void Operator delete (void * operator new [] (size_t n) {return :: operator new (n);} void Operator delete [] (void * p) {:: Operator delete (p);} // ...};
3, how is the parameter size_t incoming? When I don't call the Operator New, the compiler made a hand feet: at = new t; // Calls operator new (SIZEOF (T)); and we can also call Operator New: at = static_cast
For arrays: aryt = static_cast
4, implicit calls Operator new [], what happened?
Implicitly call Operator New [], the compiler usually distributes more memory delta: aryt = new t [5]; // Request 5 * sizeof (t) Delta Bytes
5. Use of additional memory: Used to runtime memory management, it records the array information required to release memory (the number of allocated elements, the size of each element, etc.).