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出来的对象需要销毁则调用其析构函数即可

相关推荐
wjs2024几秒前
SQL LEN() 函数详解
开发语言
姓刘的哦5 分钟前
Qt自定义控件
开发语言·qt
Ricky_Theseus6 分钟前
C++静态库
开发语言·c++
SuperEugene7 分钟前
Python 异步 async/await:为什么 AI 框架大量使用?| 基础篇
开发语言·人工智能·python
洛水水8 分钟前
【力扣100题】14.两数相加
c++·算法·leetcode
AlanW9 分钟前
# Vcpkg使用总结2
c++
我不是小upper10 分钟前
相关≠因果!机器学习中皮尔逊相关检验的完整流程
人工智能·算法·机器学习
SMF191912 分钟前
【uv】Python包管理器uv安装和应用
开发语言·python·uv
pwn蒸鱼12 分钟前
leetcode:21. 合并两个有序链表
算法·leetcode·链表
Lyyaoo.13 分钟前
【JAVA基础面经】String、StringBuffer、StringBuilder
java·开发语言