Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the C++ new operator do other than allocation and a ctor call?

What are all the other things the new operator does other than allocating memory and calling a constructor?

like image 693
yesraaj Avatar asked Dec 18 '08 08:12

yesraaj


1 Answers

The C++ standard has this to say about the single object form (the form usually used) of the new operator from the <new> header:

Required behavior:

Return a nonnull pointer to suitably aligned storage (3.7.3), or else throw a bad_alloc exception. This requirement is binding on a replacement version of this function.

Default behavior:

— Executes a loop: Within the loop, the function first attempts to allocate the requested storage. Whether the attempt involves a call to the Standard C library function malloc is unspecified.

— Returns a pointer to the allocated storage if the attempt is successful. Otherwise, if the last argument to set_new_handler() was a null pointer, throw bad_alloc.

— Otherwise, the function calls the current new_handler (18.4.2.2). If the called function returns, the loop repeats.

— The loop terminates when an attempt to allocate the requested storage is successful or when a called new_handler function does not return.

The standard has a lot of other stuff to say about the new operator and dynamic memory allocation (an awful lot to say), but I think the "Default behavior" list sums up the basics of the new operator pretty well.

like image 166
Michael Burr Avatar answered Sep 21 '22 13:09

Michael Burr