How is the C++ 'new' operator implemented

后端 未结 2 1591
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 18:22
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 wr

2条回答
  •  梦谈多话
    2021-02-04 18:49

    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::operator new(sizeof(B)))->B();
    B *b1 = static_cast(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.

提交回复
热议问题