How is the C++ 'new' operator implemented

后端 未结 2 1597
没有蜡笔的小新
没有蜡笔的小新 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:58

    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.

提交回复
热议问题