运算符new如何调用类的构造函数?
问题描述:
我知道,new运算符将调用类的构造函数.
I know that, new operator will call the constructor of class.
但是它是如何发生的,用于此的底层技术是什么.
But how it's happening, what is ground level techniques used for this.
答
这是我的想象:
T* the_new_operator(args)
{
void* memory = operator new(sizeof(T));
T* object;
try
{
object = new(memory) T(args); // (*)
}
catch (...)
{
operator delete(memory);
throw;
}
return object;
}
(*)从技术上讲,它并不是真正在调用新的位置,但是只要您不超载,心理模型就可以正常工作:)
(*) Technically, it's not really calling placement-new, but as long as you don't overload that, the mental model works fine :)