Item 37. Array Allocation

xiaoxiao2021-03-05  21

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 (Operator New) SIZEOF (T)));

For arrays: aryt = static_cast (Operator new [] (5 * sizeof (t)));

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.).

转载请注明原文地址:https://www.9cbs.com/read-33181.html

New Post(0)