New and Delete Placement Operators

I recently discovered two operators that expand on new and delete. They are known as the placement operators. Basically they allow you to allocate memory to preallocated memory, rather than calling new and delete for every object (reducing segfaults).

// --- [ includes ] -------------------------------------------
//
#include <iostream>
#include <new>
 
// --- [ class ] ----------------------------------------------
//
class Test
{
	// Attributes
	//
	private:
		int m_value;
 
	// Functions
	//
	public:
		//
		//
		Test()
			:
			m_value( 20 )
		{
		}
 
		// Set Value
		//
		void SetValue( const int inValue )
		{
			m_value = inValue;
		}
 
		// Get Value
		//
		int GetValue() const
		{
			return m_value;
		}
};
 
// --- [ entry point ] ----------------------------------------
//
void main()
{
	// 2096 Bytes of Data
	//
	char buffer[2096];
 
	// Allocate Memory from Buffer and call constructor
	//
	Test * pClass = new (buffer) Test();
 
	// Get Value set in Constructor
	//
	std::cout << "Value: " << pClass->GetValue() << std::endl;
 
	// Call Destructor
	//
	pClass->~Test();
}

 

I have to admit, there are quite a few good uses for this, I’ll probably play around with it for the next few days, see if I can find problems that may occur from using it.