Home >Backend Development >C++ >Does Placement New on Arrays Guarantee Portability in C ?

Does Placement New on Arrays Guarantee Portability in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-12 16:48:02456browse

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:

  • Manual Placement New: Rather than using placement new on the array, use it to initialize each array element individually. For instance:
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);
}
  • Manual Destruction: Manually destroy each array element before deleting the buffer to prevent memory leaks.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn