C++ placement new使用

placement new重载来原来的operator new,且placement new不能被即需重载

placement new是在原有的一块地址上继续创建一个对象,注意对象类型要一致,这样的操作的优势有两个:

1、不用花时间在找合适的空间存放新对象,减少了性能以及时间开销

2、在同一块地址生成对象,则不会另开辟空间,减少了空间开销

placement new在对时间要求特别高的时候,会经常使用

使用:

复制代码
#include "iostream"

using namespace std;

class PlaceMent {
public:
	PlaceMent(int out_value) : value(out_value) {}
	void PrintValue() {
		cout << value << endl;
	}
	~PlaceMent() {
		cout << "des" << endl;
	}
private:
	int value;
};

int main() {
	PlaceMent* rat = new PlaceMent(13);
	rat->PrintValue();
	PlaceMent* place = new(rat) PlaceMent(10);
	rat->PrintValue();
	place->PrintValue();
	int x = 100;
	cout << x << endl;
	int* mem = new(&x) int(2);
	cout << x << endl;
	cout << *mem << endl;
	place->~PlaceMent();

	return 0;
}

placement new出来的对象需要销毁则调用其析构函数即可

相关推荐
半桶水专家1 小时前
go语言中的结构体嵌入详解
开发语言·后端·golang
长安er2 小时前
LeetCode215/347/295 堆相关理论与题目
java·数据结构·算法·leetcode·
元亓亓亓2 小时前
LeetCode热题100--62. 不同路径--中等
算法·leetcode·职场和发展
在屏幕前出油2 小时前
二、Python面向对象编程基础——理解self
开发语言·python
小白菜又菜2 小时前
Leetcode 1925. Count Square Sum Triples
算法·leetcode
粉红色回忆2 小时前
用链表实现了简单版本的malloc/free函数
数据结构·c++
阿方索2 小时前
python文件与数据格式化
开发语言·python
登山人在路上3 小时前
Nginx三种会话保持算法对比
算法·哈希算法·散列表
写代码的小球3 小时前
C++计算器(学生版)
c++·算法
AI科技星3 小时前
张祥前统一场论宇宙大统一方程的求导验证
服务器·人工智能·科技·线性代数·算法·生活