new :不能被重载,其行为总是一致的。它先调用operator new分配内存,然后调用构造函数初始化那段内存。
operator new:要实现不同的内存分配行为,应该重载operator new,而不是new。
delete和 new 类似。 delete首先调用对象的析构函数,然后调用operator delete释放掉所使用的内存。
placement new:只是operator new重载的一个版本。它并不分配内存,只是返回指向已经分配好的某段内存的一个指针。因此不能删除它,但需要调用对象的析构函数。
new 操作符的执行过程
(1). 调用operator new分配内存 ;
(2). 调用构造函数生成类对象;
(3). 返回相应指针。
#include <iostream>
#include <new>
class Test
{
public:
Test()
{
std::cout << "Constructor" << std::endl;
};
~Test()
{
std::cout << "Destructor" << std::endl;
}
private:
char mA;
char mB;
};
char* gMemoryCache = (char *)malloc(sizeof(Test)); //全局变量,事先分配好内存
int main()
{
{
Test* test = new(gMemoryCache) Test();
}
{
Test* test = new(gMemoryCache) Test();
test->~Test(); // 对placement new 的对象调用析构函数
}
}
原文链接:https://blog.csdn.net/weixin_44363885/article/details/93746137