Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does memory for new have to come from operator new?

Tags:

c++

c++11

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?

like image 272
Puppy Avatar asked Nov 02 '12 16:11

Puppy


People also ask

Does new operator initialize the memory?

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.

What is the difference between new and operator new?

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.

Where does the new operator in Java allocate memory for a newly created object?

Yes, the new operator always allocates memory for the object on the heap. Unlike C++, objects in Java cannot be created on the stack.

What is the purpose of the new operator in C++?

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.


1 Answers

I think you have it the wrong way round.

The expression new T always consists of two steps:

  1. 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.

  2. 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.

like image 123
Kerrek SB Avatar answered Oct 01 '22 17:10

Kerrek SB