placement new + array +alignment

前端 未结 4 1137
鱼传尺愫
鱼传尺愫 2020-12-10 04:06
SomeObj* Buffer;
char* BufferPtr = MemoryManager::giveMeSomeBytes(resX*resY*sizeof(SomeObj));
Buffer = new(BufferPtr) SomeObj         


        
相关标签:
4条回答
  • 2020-12-10 04:37

    As others have said, this is due to your C++ implementation storing the size of the array at the start of the buffer you pass to array placement new.

    An easy fix for this is to simply assign your array pointer to the buffer, then loop over the array and use regular (non-array) placement new to construct each object in the buffer.

    0 讨论(0)
  • 2020-12-10 04:41

    @Mat, This is actually a great question. When I've used placement new[], I've had trouble deleting the storage. Even if I call my own symmetrical placement delete[], the pointer address is not the same as was returned by my own placement new[]. This makes placement new[] completely useless, as you've suggested in the comments.

    The only solution I've found was suggested by Jonathan@: Instead of placement new[], use placement new (non-array) on each of the elements of the array. This is fine for me as I store the size myself. The problem is that I have to worry about pointer alignments for elements, which new[] is supposed to do for me.

    0 讨论(0)
  • 2020-12-10 04:45

    You're using the array version of the new operator which in your implementation is storing information about the array size in the first few bytes of the memory allocation.

    0 讨论(0)
  • 2020-12-10 04:56

    Be careful with placement new on arrays. In the current standard look to section 5.3.4.12, you'll find this:

    new(2,f) T[5] results in a call of operator new[](sizeof(T)*5+y,2,f)
    

    It is clear that it will expect the placement new operator to allocate it additional space beyond what the array contents need. "y" is specified only as a non-negative integral value. It will then offset the result of the new function by this amount.

    Also look to 18.4.1.3.4 where it says the placement new operator simply returns the provided pointer. This is obviously the expected part.

    Based on 5.3.4.12, since that offset may be different for every invocation of the array, the standard basically means there is no way to allocate the exact amount of size needed. In practice that value is probably constant and you could just add it to the allocation, but his amount may change per platform, and again, per invocation as the standard says.

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