In what way is ::operator new[]() different than ::operator new()?

前端 未结 2 1050
清酒与你
清酒与你 2021-01-21 04:11

I need to construct an array of objects from a previously allocated block of memory. However, I cannot understand in what way ::operator new[]() is different from <

相关标签:
2条回答
  • 2021-01-21 04:38

    They're both allocation functions and thus they're both mandated to return suitable storage for the requested size (here that's sizeof(J) * size). That's why they make no difference in your code.

    Where they differ is that operator new is the allocation function that is looked up in a non-array new expression (e.g. new J), whereas operator new[] is the allocation function that is looked up in an array new expression (e.g. new J[1]). This allows customization if a program has a particular strategy to allocate memory for arrays that differ from the strategy for allocating memory for single objects. If no such customization is needed then operator new[] can just delegate to operator new (and this is in fact what is mandated for the allocation functions provided by the implementations, i.e. ::operator new and ::operator new[]). So that difference isn't relevant for your code.

    0 讨论(0)
  • 2021-01-21 04:48

    You're misusing the new.

    The point of using new [] is that it calls the constructor for each and every element of the array being allocated. delete[] does the same for the destructors.

    You're using placement new and manually calling the constructors and destructors, missing the whole point.

    0 讨论(0)
提交回复
热议问题