Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does new return (void *) in C++?

Tags:

c++

This is a simple question :

Does using new operator return a pointer of type (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 it returns a pointer of type (void *), if it returns (void *) I have never seen a code like MyClass *ptr = (MyClass *)new MyClass;

I have got confused .

EDIT

As per 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);
it should return (void *) if I understand the syntax correctly.

Thanks

like image 241
Gaurav K Avatar asked May 02 '13 18:05

Gaurav K


People also ask

What does new return in C?

Since new is a language keyword and not a function, it doesn't "return" anything.

What is return type void * in C?

The void type, in several programming languages derived from C and Algol68, is the return type of a function that returns normally, but does not provide a result value to its caller. Usually such functions are called for their side effects, such as performing some task or writing to their output parameters.

What does void * function return?

A void function cannot return any values. But we can use the return statement. It indicates that the function is terminated. It increases the readability of code.

What is returned by new operator?

In short: The new operator returns the unique address of the allocated object. When you allocate an array of objects the address of the first object is returned.


1 Answers

You are confusing operator new (which does return void*) and the new operator (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
like image 191
john Avatar answered Sep 20 '22 04:09

john