3

when I'm doing the following :

T* ptr2 = new (ptr1) T();

I obtain ptr1 == ptr2

When I'm doing :

T* ptr2 = new (ptr1) T[6];

I obtain, under MSVC 2012 in debug, ptr2 > ptr1 (off by 3 bytes)

However the code in the "new" file is :

inline void *__CRTDECL operator new[](size_t, void *_Where) _THROW0()
    {   // construct array with placement at _Where
    return (_Where);
    }

I'm assuming that some debug info are added but I can't make sense of this

The initial ptr1 is obtained through malloc, so I think it's supposed to be aligned to any possible type, so I don't think that alignment is an issue.

Am I doing something that should not be working here ? Why would ptr2 != ptr1 ? Thanks!

lezebulon
  • 7,607
  • 11
  • 42
  • 73
  • 1
    Array `new` will store some extra overhead (for the size of the array), and since the amount of overhead is unspecified, it's usually not a great idea to use placement array new. – T.C. Oct 17 '14 at 23:26
  • @T.C. are you sure ? I don't see why it would be needed because the memory is managed by the caller, plus I don't see it in the implementation file – lezebulon Oct 17 '14 at 23:29
  • http://stackoverflow.com/questions/8720425/array-placement-new-requires-unspecified-overhead-in-the-buffer. The overhead part is handled by the compiler directly, not in the placement new function. – T.C. Oct 17 '14 at 23:30
  • ok I see that's a bit annoying. As far as I can tell MSVC uses the extra space to count how many elements there are in the array. However this value is only ever used when calling delete[] to find out how many objects there is to loop through for the dtors. In that specific case this is useless because I won't ever call delete[] but I will manually loop through the object and call their destructor – lezebulon Oct 17 '14 at 23:44
  • I'd say this is a perfect duplicate of what T.C. linked. – Marco A. Oct 18 '14 at 08:47

1 Answers1

0

I don't think C++ placement new is strictly required to place the beginning of the object that client code can see, at the beginning of the buffer that you passed to new.

It's only required to place it somewhere inside it. It's completely cool for the compiler to do anything it wants to with the space, provided it doesn't have allocate any buffers anywhere else.

So you should not be depending on ptr1 and ptr2 having the same value, for any use of placement new, not just this one.

I'm not dead certain of this though. I could be wrong.

Mike Crawford
  • 2,232
  • 2
  • 18
  • 28