C++ placement new use

placement new overloads the original operator new, and placement new cannot be overloaded on demand

Placement new is to continue to create an object at the original address. Note that the object type must be consistent. There are two advantages of such an operation:

1. No need to spend time looking for suitable space to store new objects, which reduces performance and time overhead.

2. Generating objects at the same address will not open up additional space, reducing space overhead.

Placement new is often used when time requirements are particularly high.

use:

#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;
}


If the object from placement new needs to be destroyed, just call its destructor.

Guess you like

Origin blog.csdn.net/qqQQqsadfj/article/details/133031992