C++中- placement new

An operator new

void* operator new (std::size_t size) throw (std::bad_alloc);
void* operator new (std::size_t size, const std::nothrow_t& nothrow_constant) throw();
void* operator new (std::size_t size, void* ptr) throw();

  1. The first type allocates size bytes of storage space and aligns the object types in memory. If successful, return a non-null pointer to the first address. If it fails, a bad_alloc exception is thrown.
  2. The second type does not throw an exception when the allocation fails, it returns a NULL pointer.
  3. The third is the placement new version. It does not allocate memory, calls the appropriate constructor to construct an object at the place pointed to by ptr, and then returns the actual parameter pointer ptr.

A* a = new A; //call the first type
A* a = new(std::nothrow) A; //call the second type
new §A(); //call the third type, where p can be The dynamically allocated memory in the heap can also be buffered in the stack.

Two placement new example

class TestA
{
    
    
public:
	void show()
	{
    
    
		cout << "num:" << num << endl;
	}
private:
	int num;
};

int main()
{
    
    
	{
    
    
		cout << "栈" << endl;
		char array_c[10];
		array_c[0] = '\0';
		array_c[1] = '\0';
		array_c[2] = '\0';
		array_c[3] = '\0';
		cout << (void*)array_c << endl;
		TestA* p = new (array_c)TestA;
		cout << p << endl;
		p->show();
		//delete p; 栈空间 第二次系统回收资源,会崩溃
	}

	{
    
    
		cout << endl;
		cout << "堆" << endl;
		char * parray_c = new char[10];
		parray_c[0] = '\0';
		parray_c[1] = '\0';
		parray_c[2] = '\0';
		parray_c[3] = '\0';
		cout << (void*)parray_c << endl;
		TestA* pA = new (parray_c)TestA;
		cout << pA << endl;
		pA->show();
		delete pA;
	}
	getchar();
	return 0;
}

result
Insert picture description here

Guess you like

Origin blog.csdn.net/GreedySnaker/article/details/114068084
Recommended