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
197 views
in Technique[技术] by (71.8m points)

c++ - Why is the new operator allowed to return *void to every pointer-type?

In C++ it is not allowed to assign an void* pointer to any integral pointer without an explicit cast. This requires the use of an static_cast.

But what is with this:

int* iptr = new int;

I know that new operator is defined as following:

void* operator new(size_t);

How does C++ handle this? I know that this is a basic question, but important. I also know that low-level code must use void. But how can this assignment be legal? iptr is a pointer to an int and new returns a pointer to void, which should trigger a message like "error: invalid conversion from ‘void*’ to ‘int*’ [-fpermissive]".

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You have confused the new operator and the operator new function. No problem, everybody does. They are almost the same, except that they are different.

The function void* operator new(size_t) grabs a block of raw, untyped memory from whatever tree it grows on, and returns it to the program.

void* raw_memory = ::operator new(42);

It is an ordinary function with somewhat weird name.

The new operator is not a function and not a function call. It's a separate language construct. It takes raw memory (normally, one returned by the void* operator new(size_t) function) and turns it into an object by calling a constructor. It then returns a properly typed pointer to the newly-created object.

Fish* f = new Fish;

UPDATE Naturally, there is also the delete operator (the opposite of the new operator) and the void operator delete(void*) function (the opposite of the void* operator new(size_t) function).

There are also the new[] operator, the delete[] operator, the void* operator new[](size_t) function, and the void operator delete[](void*) function; they deal with arrays of objects (as opposed to individual objects).

There are also so-called "placement new" forms that do not call any of the operator new functions for fresh memory, but instead require an explicit pointer to raw memory. They have no corresponding built-in "delete" forms. You can roll your own if you are so inclined, but I refuse to talk about any of this while being sober.


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

...