C ++的"new"运算符是如何实现的 [英] 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)
但是,如果我们要编写new
的自定义版本,则语法为
However, if we want to write a custom version of new
, the syntax is
Class B
{
/*...*/
static void* operator new(size_t size);
}
如何将语句new B()
转换为的函数调用
operator new(sizeof(B))
?
How is the statement new B()
converted to a function call for
operator new(sizeof(B))
?
如何跟踪要调用的构造函数,即如何区分new B()
和new B(int x)
?
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)
?
new
是否在C ++中实现为宏?
Is new
implemented as a macro in C++?
推荐答案
您的问题应该是:
当
B::operator new
语法相同时,编译器如何区分new B()
和new B(10)
?
How compiler distinguish between
new B()
andnew B(10)
, when theB::operator new
syntax is same ?
好吧,new
只分配内存,然后编译器立即将调用插入构造函数.因此,与调用new B
,new B()
或new B(10)
无关.
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)
.
编译器解释如下:
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.
这篇关于C ++的"new"运算符是如何实现的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!