Chapter 12. New and Delete
FAQ 12.01 Does new
do more than allocate memory?
Yes, it also initializes the new object.
Assuming Fred
is a known type, the expression new Fred()
is a two-step operation. The first step is to allocate sizeof(Fred)
bytes of memory using a memory allocator primitive called operator new(size_t nbytes
) (size_t
is a typedef
for an unsigned
integral type such as unsigned int
). This memory allocation primitive is conceptually similar to but not interchangeable with malloc(size_t nbytes)
. The second step is to call the appropriate constructor of the class (Fred::Fred()
in this case).
Similarly, delete p
is a two-step operation: it first calls the destructor on the object *p
, then it releases the memory pointed to by p
using ...
Get C++ FAQs, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.