Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is return type of new in c++?

Tags:

c++

in C, malloc() returns void*. But in C++, what does new return?

double d = new int;
like image 267
kam Avatar asked Apr 23 '10 10:04

kam


People also ask

What is returned by new operator?

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.

What is return type in C?

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.

What is the use of new in C?

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.

What is the new operator?

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.


2 Answers

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);
like image 186
sbi Avatar answered Sep 25 '22 17:09

sbi


Type of value returned from both new Type[x] and new Type is Type *. Your example double d = new int contains two errors:

  • you need to assign the result into a pointer, like this: double *d = new int
  • the pointer needs to be a pointer to Type or something to which can a pointer to Type be converted using implicit conversions: int *d = new int or void *d = new int
like image 39
Suma Avatar answered Sep 22 '22 17:09

Suma