什么是c ++中的新的返回类型? [英] what is return type of new in c++?
问题描述
在C中, malloc()
返回 void *
。但在C ++中, new
会返回什么?
in C, malloc()
returns void*
. But in C++, what does new
return?
double d = new int;
推荐答案
一个是 新表达式 。它是表达式 new T
,其结果是 T *
。它做两件事:首先,它调用 new运算符来分配内存,然后它调用T.的构造函数
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.)
上述 新运算符 / strong>,但是,有几种口味。最突出的是这一个:
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.
还有其他形式的 new运算符,例如数组
There are other forms of the new operator, for example for arrays
void* operator new[](std::size_t);
或所谓的 placement new new,因为它不分配):
or the so-called placement new (which really is a fake-new, since it doesn't allocate):
void* operator new(void*, std::size_t);
这篇关于什么是c ++中的新的返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!