Placement New for Arrays: A Guide to Portable Usage
While placement new offers a powerful tool for array allocation, ensuring its portability can be a challenge. As observed in the provided example, Visual Studio can allocate buffers that differ from the address passed to new[], potentially leading to memory corruption.
Understanding the Overhead
The overhead involved in using placement new on arrays is compiler-dependent. In Visual Studio, the compiler adds a four-byte count to the buffer to track the number of elements in the array. This count is crucial for invoking object destructors when the array is deleted.
Portable Alternatives
To address the portability issue, consider the following alternatives:
Separate Placement New for Each Element:
Instead of using placement new for the entire array, allocate each element individually:
char *pBuffer = new char[NUMELEMENTS * sizeof(A)]; A *pA = (A*)pBuffer; for (int i = 0; i < NUMELEMENTS; ++i) { pA[i] = new (pA + i) A(); }
This approach eliminates the need for additional overhead and ensures portability.
Manual Object Destruction:
Regardless of the allocation method, ensure that each object in the array is manually destroyed before deleting the buffer:
for (int i = 0; i < NUMELEMENTS; ++i) { pA[i].~A(); }
This step prevents memory leaks and ensures proper object cleanup.
Memory Tracking Overhead
It's important to note that the compiler's overhead for memory tracking varies. For example, in Visual Studio, removing the virtual destructor from the class eliminates the need for the four-byte count. Understanding the memory tracking requirements of your specific compiler can help you optimize performance.
The above is the detailed content of Can Placement New for Arrays Be Used Portably?. For more information, please follow other related articles on the PHP Chinese website!