New return (void *) in C ++?

This is a simple question:

Does the new operator use a type pointer (void *)? Referring to What is the difference between new / delete and malloc / free? answer - it says new returns a fully typed pointer while malloc void *

But according to http://www.cplusplus.com/reference/new/operator%20new/

 throwing (1) void* operator new (std::size_t size) throw (std::bad_alloc); nothrow (2) void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) throw(); placement (3) void* operator new (std::size_t size, void* ptr) throw(); 

which means that it returns a pointer of type (void *), if it returns (void *), I never saw code like MyClass * ptr = (MyClass *) new MyClass;

I'm confused.

EDIT

By http://www.cplusplus.com/reference/new/operator%20new/ example

 std::cout << "1: "; MyClass * p1 = new MyClass; // allocates memory by calling: operator new (sizeof(MyClass)) // and then constructs an object at the newly allocated space std::cout << "2: "; MyClass * p2 = new (std::nothrow) MyClass; // allocates memory by calling: operator new (sizeof(MyClass),std::nothrow) // and then constructs an object at the newly allocated space 

So, MyClass * p1 = new MyClass calls operator new (sizeof(MyClass)) , and since throwing (1)
void* operator new (std::size_t size) throw (std::bad_alloc);
throwing (1)
void* operator new (std::size_t size) throw (std::bad_alloc);
it should return (void *) if I understand the syntax correctly.

thanks

+6
source share
3 answers

You are misleading operator new (which returns void* ) and operator new (which returns a fully typed pointer).

 void* vptr = operator new(10); // allocates 10 bytes int* iptr = new int(10); // allocate 1 int, and initializes it to 10 
+14
source

void * does not need to be cast to a higher type when only the old c code is assigned before void * requires casting because the old malloc signature returned instead of char * .

0
source

new will return a pointer to what ever created the instance. operator new returns a pointer to void. new pretty common, and operator new is a bit more unique.

0
source

Source: https://habr.com/ru/post/944151/


All Articles