How the C ++ operator 'new' is 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

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

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

And how does it track which constructor to invoke, that is, how does it distinguish between new B() and new B(int x) ?

Is new implemented as a macro in C ++?

+4
source share
2 answers

Your question should be:

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

Well, new just allocates memory , and right after that, the compiler inserts a call to the constructor. Therefore, regardless of whether you call new B , new B() or new B(10) .

The 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 fact, the constructor returns nothing. But the above pseudo-code is just an analog representation of the internal material.

+5
source

The question of which constructor to call is a matter of resolving overloads based on a list of arguments, is similar to any overloaded function call. At the place where the new B (...) is found, all information is available. The compiler can resolve the reference to class B (search for a name) and see the portfolio of available constructors, and also see that B has its own memory allocation mechanism. The compiler can emit code to use this memory allocator to get space (passing in size B), and then call the appropriate constructor code to initialize the object in that space.

0
source

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


All Articles