开发者

what is return type of new in c++?

开发者 https://www.devze.com 2022-12-28 10:31 出处:网络
in C, malloc() returns void*. But in C++, what does new return? 开发者_如何学JAVAdouble d = new int;

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

开发者_如何学JAVA
double d = new int;


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:

  • 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
0

精彩评论

暂无评论...
验证码 换一张
取 消