对于自定义对象,我们可以重载普通new操作符,这时候使用new Test()时就会调用到我们重载的普通new操作符。
示例程序:
#include <iostream>
#include <cstdlib> using namespace std; class Test
{
public:
Test()
{
cout << "Test()" << endl;
} void* operator new(unsigned int size)
{
void* ret = malloc(sizeof(int) * size); cout << "normal new" << endl; return ret;
} }; int main()
{
Test* t = new Test(); Test t2; return ;
}
执行结果如下:
调用placement new,程序如下:
#include <iostream>
#include <cstdlib> using namespace std; class Test
{
public:
Test()
{
cout << "Test()" << endl;
} void* operator new(unsigned int size)
{
void* ret = malloc(sizeof(int) * size); cout << "normal new" << endl; return ret;
} }; int main()
{
Test* t = new Test(); Test* t1 = new((void*)t)Test(); Test t2; return ;
}
编译结果如下:
提示我们没有对应的函数,也就是placement new没有重载。
更改程序:
#include <iostream>
#include <cstdlib> using namespace std; class Test
{
public:
Test()
{
cout << "Test()" << endl;
} void* operator new(unsigned int size)
{
void* ret = malloc(sizeof(int) * size); cout << "normal new" << endl; return ret;
} void* operator new(unsigned int size, void* loc)
{
cout << "placement new" << endl;
return loc;
} }; int main()
{
Test* t = new Test(); Test* t1 = new((void*)t)Test(); Test t2; return ;
}
结果如下:
再次给出一个测试程序:
#include <iostream>
#include <cstdlib> using namespace std; class Test
{
public:
Test()
{
cout << "Test()" << endl;
} void* operator new(unsigned int size)
{
void* ret = malloc(sizeof(int) * size); cout << "normal new" << endl; return ret;
} void* operator new(unsigned int size, void* loc)
{
cout << "placement new" << endl;
return loc;
} }; int main()
{
Test* t = new Test(); Test* t1 = new((void*)t)Test(); Test t2; Test* t3 = new((void*)&t2)Test(); int a = ; int* p = new((void*)&a)int(); cout << "a = " << a << endl; return ;
}
运行结果如下:
可以看到普通内置类型可以直接使用placement new。