Difficulty: Easy
Correct Answer: delete[]
Explanation:
Introduction / Context:
Managing dynamic memory safely in C++ requires using the correct deallocation form that matches the allocation form. When arrays of objects are involved, each element may hold resources that must be released via its destructor. This question focuses on the precise operator syntax that guarantees all destructors are invoked.
Given Data / Assumptions:
Concept / Approach:
In C++, allocation and deallocation forms must match. If you allocate with new[], you must deallocate with delete[]. Using plain delete on memory obtained via new[] yields undefined behavior and typically destroys only the first element, skipping the rest. The pairings are: new ↔ delete, and new[] ↔ delete[].
Step-by-Step Solution:
1) Allocate: T* p = new T[n];2) Use the array p[0] ... p[n-1] as needed.3) Deallocate correctly: delete[] p; // invokes ~T() for each element, then frees memory4) Avoid: delete p; // incorrect for arrays; may leak resources and causes undefined behavior
Verification / Alternative check:
Instrument ~T() to log. With delete[] p, logs appear n times in reverse order of construction. With incorrect delete p, only one log may appear, confirming the mismatch problem.
Why Other Options Are Wrong:
destructor: not an operator; you do not call destructors on arrays manually.kill[] / free[]: not C++ operators; free is a C function for malloc-based memory, not new[].delete: correct only for single-object allocations done with new, not arrays.
Common Pitfalls:
Mixing allocation APIs (new/new[] with malloc/free) and forgetting to use delete[] for arrays. Prefer smart pointers or standard containers (std::vector) to avoid manual memory management.
Final Answer:
delete[]
Discussion & Comments