string *ptr = new string("Hello");
The new operator mainly does two things:
-
It allocates enough memory to hold an object of the type requested.
(In the above example, it allocates enough memory to hold this string object)- It calls a constructor to initialize an object in the memory that was allocated.
Now this “new” is calling which function?
It is operator new.
void * operator new (size_t size);
The return type is void*.
Since this function returns a pointer to raw which is not typed and uninitialized memory large enough to hold an object of the specified type.
The size_t specifies how much memory to allocate.
If we call operator new directly , it returns a pointer to a chunk of memory enough to hold a string object.
void *pointRawMemory = operator new(sizeof(string));
The operator new is similar to malloc. It is responsible only for allocating memory. It knows nothing about constructors.
It is the job of the “new” operator to take the raw memory that the operator new returns and make it into an object.
solved Relation between “new” and “operator new” [closed]