Vì sao new/delete và new[]/delete[] phải được ghép đúng, và RAII alternative nào tránh được vấn đề?
Xem đáp án và giải thích
Pointer do ordinary new-expression trả về phải đi vào single-object delete tương ứng, còn storage từ new[] expression cần delete[]. Array form destroy các element đã construct và gọi matching deallocation function; dùng sai form gây undefined behavior kể cả khi trivial element type có vẻ vẫn chạy. Nên ưu tiên value, std::vector cho sequence động, std::array cho fixed-size value storage hoặc std::unique_ptr<T[]> khi thật sự cần dynamically allocated array. Các owner này giữ đúng destruction policy qua exception và early return.
Pointer do ordinary new-expression trả về phải đi vào single-object delete tương ứng, còn storage từ new[] expression cần delete[]. Array form destroy các element đã construct và gọi matching deallocation function; dùng sai form gây undefined behavior kể cả khi trivial element type có vẻ vẫn chạy. Nên ưu tiên value, std::vector cho sequence động, std::array cho fixed-size value storage hoặc std::unique_ptr<T[]> khi thật sự cần dynamically allocated array. Các owner này giữ đúng destruction policy qua exception và early return.
Hãy liên hệ trực tiếp kết luận với kiểu, lifetime, ownership, overload resolution hoặc library contract xuất hiện trong câu hỏi. Nếu kết quả phụ thuộc implementation hoặc vi phạm precondition, cần nói rõ thay vì chỉ đoán output.