Portable Placement New for Arrays
The standard library's placement new operator allows for the allocation of memory at a specified address. However, its use with arrays raises concerns about portability due to potential discrepancies between the returned pointer and the address passed in.
Understanding the Problem
When using placement new for arrays, the returned pointer may not align with the address provided. This is explained in Note 12 of 5.3.4 of the C standard. Consequently, allocating a buffer specifically for the array becomes problematic.
Consider the following example:
#include <iostream> #include <new> class A { public: A() : data(0) {} ~A() {} int data; }; int main() { const int NUMELEMENTS = 20; char *pBuffer = new char[NUMELEMENTS * sizeof(A)]; A *pA = new(pBuffer) A[NUMELEMENTS]; // Output may show pA as four bytes higher than pBuffer std::cout << "Buffer address: " << pBuffer << ", Array address: " << pA << std::endl; delete[] pBuffer; return 0; }
This example often results in memory corruption under Microsoft Visual Studio. Examination of the memory reveals that the compiler prefixes the array allocation with four bytes, likely storing the count of array elements. This behavior varies depending on the compiler and class used.
Portable Solution
To address this portability issue, avoid using placement new directly on arrays. Instead, consider allocating each element of the array individually using placement new:
#include <iostream> #include <new> class A { public: A() : data(0) {} ~A() {} int data; }; int main() { const int NUMELEMENTS = 20; char *pBuffer = new char[NUMELEMENTS * sizeof(A)]; A *pA = (A*)pBuffer; for (int i = 0; i < NUMELEMENTS; ++i) { pA[i] = new (pA + i) A(); } std::cout << "Buffer address: " << pBuffer << ", Array address: " << pA << std::endl; // Remember to manually destroy each element for (int i = 0; i < NUMELEMENTS; ++i) { pA[i].~A(); } delete[] pBuffer; return 0; }
Regardless of the approach taken, manually destroying each array element before deleting the buffer is crucial to prevent memory leaks.
The above is the detailed content of Is Using Placement New on C Arrays Portable?. For more information, please follow other related articles on the PHP Chinese website!