Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the C++ 'new' operator implemented

Class B;
B *b  = new B();       // default constructor
B *b1 = new B(10);     // constructor which takes an argument B(int x)

However, if we want to write a custom version of new, the syntax is

Class B
{
  /*...*/
  static void* operator new(size_t size);
}

How is the statement new B() converted to a function call for operator new(sizeof(B))?

And how does it keep track of which constructor to call i.e. how does it distinguish between new B() and new B(int x)?

Is new implemented as a macro in C++?

like image 794
vamsi Avatar asked Mar 07 '12 04:03

vamsi


People also ask

How is new operator implemented C++?

When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator. Use the delete[] operator to delete an array allocated by the new operator.

How does the new operator work?

The new operator is an operator which denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.

Does C have new operator?

There's no new / delete expression in C. The closest equivalent are the malloc and free functions, if you ignore the constructors/destructors and type safety.

What is new operator in C give example?

For example: int *a=new int; In the above example, the new operator allocates sufficient memory to hold the object of datatype int and returns a pointer to its starting point. The pointer variable holds the address of memory space allocated.


1 Answers

Your question should be:

How compiler distinguish between new B() and new B(10), when the B::operator new syntax is same ?

Well, new just allocates the memory and immediately after that the compiler inserts the call to the constructor. So it's irrespective if you call new B, new B() or new B(10).

Compiler interprets something like:

B *b = static_cast<B*>(B::operator new(sizeof(B)))->B();
B *b1 = static_cast<B*>(B::operator new(sizeof(B)))->B(10);

In actual a constructor doesn't return anything. But above pseudo code is just an analogical representation of internal stuff.

like image 130
iammilind Avatar answered Sep 29 '22 01:09

iammilind