in C, malloc()
returns void*
. But in C++, what does new
return?
double d = new int;
In short: The new operator returns the unique address of the allocated object. When you allocate an array of objects the address of the first object is returned.
Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name − This is the actual name of the function.
The new operator requests for the memory allocation in heap. If the sufficient memory is available, it initializes the memory to the pointer variable and returns its address.
The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
There's two things you have to distinguish. One is a new expression. It is the expression new T
and its result is a T*
. It does two things: First, it calls the new operator to allocate memory, then it invokes the constructor for T. (If the constructor aborts with an exception, it will also call the delete operator.)
The aforementioned new operator, however, comes in several flavours. The most prominent is this one:
void* operator new(std::size_t);
You could call it explicitly, but that's rarely ever done.
There are other forms of the new operator, for example for arrays
void* operator new[](std::size_t);
or the so-called placement new (which really is a fake-new, since it doesn't allocate):
void* operator new(void*, std::size_t);
Type of value returned from both new Type[x]
and new Type
is Type *
. Your example double d = new int
contains two errors:
double *d = new int
int *d = new int
or void *d = new int
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