Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

what is return type of new in c++?

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

double d = new int;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...