How is the C++ 'new' operator implemented

风格不统一 提交于 2019-12-03 13:32:10

问题


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++?


回答1:


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.




回答2:


The question of which constructor to call is a matter of overload resolution based on the argument list, similar to any overloaded function call. At the site where new B(...) occurs, all the information is available. The compiler can resolve the reference to class B (name lookup), and see the portfolio of constructors available, and also see that B has a custom memory allocator mechanism. The compiler can emit the code to use that memory allocator to get the space (passing in the size of B), and then invoke appropriate constructor code to initialize the object in that space.



来源:https://stackoverflow.com/questions/9595758/how-is-the-c-new-operator-implemented

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!