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