对于自定义对象,我们可以重载普通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。

最新文章

  1. AngularJS 细节
  2. PropertyMetadata和UIPropertyMetadata的一点区别
  3. myeclipse的项目导入到eclipse下,com.sun.org.apache.commons.beanutils.BeanUtils不能导入
  4. jquery过滤器
  5. Mac下好用的取色器 Sip
  6. 310. Minimum Height Trees
  7. 关于extjs中动态添加TabPanel的tab项并以iframe显示的整理
  8. ThinkPad New X1 Carbon中关闭任务栏上的触摸键盘
  9. flowplayer+flashhls使用过程中发现的一些小问题
  10. HTML5的绘图的支持
  11. 深入浅出MyBatis-Sqlsession
  12. 登录SQL注入
  13. 学Java,是自学还是去培训班学习?
  14. uva211 回溯
  15. Linux 基本概念和操作
  16. linux2.6内核链表
  17. Jenkins+Ansible+Gitlab自动化部署三剑客-Ansible本地搭建
  18. SSLv3存在严重设计缺陷漏洞(CVE-2014-3566)
  19. iot平台在k8s搭建过程
  20. Scrapy实践----获取天气信息

热门文章

  1. Leetcode 124 *
  2. echarts3使用总结2
  3. 将本地项目推送至gitee或者github
  4. Oracle常用表和常见操作命令
  5. jackSon注解– @JsonInclude 注解不返回null值字段
  6. JS--label语句的使用
  7. unity中实现三个Logo图片进行3秒钟的若隐若现后互相切换Logo图片
  8. python使用变量
  9. tomcat 服务器线程问题
  10. RabbitMQ Dead Lettering(死信)