C ++: new positioning expression


new positioning expression (placement-new)

The new positioning expression is to call the constructor to initialize an object in the allocated original memory space.

Use format:

  • new (pointer) type

  • new (place_address) typeornew (place_address) type(initializer-list)

  • place_addressMust be a pointer, initializer-listan initialized list of types

scenes to be used:

The new positioning expression is generally used in conjunction with the memory pool in practice . Because the memory allocated by the memory pool is not initialized, if it is a custom type object, you need to use the new definition expression to display the constructor to initialize.

Code example:

class Test
{
public:
	Test(): 
		_data(0)
	{
		cout << "Test():" << this << endl;
	}
	~Test() {
		cout << "~Test():" << this << endl;
	}
private:
	int _data;
};

void test() {
	// pt现在指向的只不过是与Test对象相同大小的一段空间,还不能算是一个对象,因为构造函数没有执行 
	Test* pt = (Test*)malloc(sizeof(Test));

	new(pt) Test; // 注意:如果Test类的构造函数有参数时,此处需要传参 
}

The space applied by the new positioning expression does not actually open up new space , so there is no need to release through delete . If you want to call the destructor, you can use the explicit call method, for example: through pd-> ~ Data (); destruct.

Code example:

class Date {
	int m_year;
	_uint m_month;
	_uint m_day;
public:
	Date(int y, _uint m, _uint d) :
		m_year(y),
		m_month(m),
		m_day(d)
	{
	}
};

int main() {
	char* pa = new char[1024];
	size_t size = 0;

	Date* pd = new(pa + size)Date(2020, 01, 16);

	pd->~Date();
	delete pa;

	return 0;
}
Published 152 original articles · praised 45 · 10,000+ views

Guess you like

Origin blog.csdn.net/AngelDg/article/details/104918767