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

猜你喜欢

转载自blog.csdn.net/qqQQqsadfj/article/details/133031992