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

相关推荐
da-peng-song6 分钟前
ArcGIS Desktop使用入门(二)常用工具条——数据框工具(旋转视图)
开发语言·javascript·arcgis
galaxy_strive6 分钟前
qtc++ qdebug日志生成
开发语言·c++·qt
TNTLWT9 分钟前
Qt功能区:简介与安装
开发语言·qt
Hygge-star14 分钟前
【数据结构】二分查找5.12
java·数据结构·程序人生·算法·学习方法
Darkwanderor23 分钟前
c++STL-list的模拟实现
c++·list
Humbunklung1 小时前
Visual Studio 2022 中添加“高级保存选项”及解决编码问题
前端·c++·webview·visual studio
等等5431 小时前
Java EE初阶——wait 和 notify
java·开发语言
小乌龟不会飞1 小时前
gflags 安装及使用
c++·mfc·gflags 库
低代码布道师1 小时前
第五部分:第一节 - Node.js 简介与环境:让 JavaScript 走进厨房
开发语言·javascript·node.js
June`2 小时前
专题二:二叉树的深度搜索(二叉树剪枝)
c++·算法·深度优先·剪枝