Home >Backend Development >C++ >Does Placement New on Arrays Guarantee Portability in C ?
Can Placement New for Arrays Ensure Portability?
While placement new provides a means to initialize arrays in C , its use for arrays introduces potential portability issues. Specifically, the pointer obtained from new[] may deviate from the provided address, hindering buffer allocation for the array.
The standard's 5.3.4, note 12, acknowledges this discrepancy, making it challenging to allocate a buffer of the appropriate size for the array. An example highlights the issue:
int main() { const int NUMELEMENTS = 20; char *pBuffer = new char[NUMELEMENTS * sizeof(A)]; A *pA = new(pBuffer) A[NUMELEMENTS]; // With Visual Studio, pA will be four bytes higher than pBuffer printf("Buffer address: %x, Array address: %x\n", pBuffer, pA); }
In this example, the compiler appears to store a count of array elements in the buffer's first four bytes. As a result, memory corruption occurs because the buffer is allocated with only sizeof(A) * NUMELEMENTS bytes of space.
Avoiding Portability Concerns:
To mitigate these portability issues, consider the following approach:
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(); } printf("Buffer address: %x, Array address: %x\n", pBuffer, pA); }
It's important to note that the additional overhead for placement new[] can vary depending on the implementation and class definition. Nonetheless, this manual approach ensures portability across different compilers and eliminates the need to ascertain the overhead dynamically.
The above is the detailed content of Does Placement New on Arrays Guarantee Portability in C ?. For more information, please follow other related articles on the PHP Chinese website!