tags:

views:

302

answers:

2

Hi All,

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

double d = new int;

Thanks, Arul

+4  A: 

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
Suma
+15  A: 

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);
sbi
For example int *p = new int, it returns int*, then how signature has void*?
kam
Great answer to a silly question. The poster does not seem to have any idea of how "new" fits into the language. The answer explains this very nicely.
Suma
"int p = new int, it returns int," It does not. I returns int * (pointer to int).
Suma
@kam: `<sigh>` Read again. `new int` is a __new expression__. The language defines that it returns an `int*`. Among other things it also calls the __new operator__, which, yes, returns a `void*`, because it just allocates raw storage. The constructor (empty for `int`) turns raw storage into an initialized object. You could think of this as the transformation from `void*` to `int*` if you like.
sbi
`new T` does not evaluate to `T*` for arrays, though.
Johannes Schaub - litb
@Johannes: That would be `new T[N]`. The result is certainly compatible with `T*` and if it's indeed not the same, then it is close enough for the OP. Still, I have to ask: What is "`ElementTypeOfT`"???
sbi
@sbi, if `T` is an array type, then `new T` is not compatible with `T*`. That's all i want to say :) It doesn't depend on whether you write brackets or not. It depends on the type. (imagine that `T` can be a typedef for an array type or a template parameter passed an array type). Thus in a template `T * t = new T;` is not correct for arrays.
Johannes Schaub - litb
Ouch. Indeed, `T` could be a `typedef` for a array. I would have never thought of this. Well, considering the question, I still guess we can skip over this detail, but I marvel at your attention for detail.
sbi