When considering something along the lines of
auto x = new T;
Does the Standard enforce that the memory must come from operator new
- class-specific or global? i.e., there is no way a conforming implementation, given a lack of a class-specific operator new
, could get the memory from anywhere except the global operator new
?
The new operator is an operator which denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.
There's no difference between "new operator" and "operator new". Both refer to the same thing: the overloadable/replaceable operator new function that typically performs raw memory allocation for objects created by new-expressions.
Yes, the new operator always allocates memory for the object on the heap. Unlike C++, objects in Java cannot be created on the stack.
The new operator is used to initialize the memory and return its address to the pointer variable ptr1 and ptr2. Then the values stored at memory positions pointed to by ptr1 and ptr2 are displayed. Finally the delete operator is used to free the memory.
I think you have it the wrong way round.
The expression new T
always consists of two steps:
A suitable operator new
is searched for. If one exists in the class T
, that one is taken, otherwise the global one is taken. The global one always exists, as this is mandated by the standard (so you can never "define" it (since it is already defined), but you can replace it).
You can say ::new T
to always pick the global operator new
unconditionally.
Once the allocation function has been called and succeeded, the object is constructed in that memory.
If you say new (a, b, c) T
, then the same happens, only that in step 1 we are now looking for an operator new
overload with the appropriate signature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With