Practical answer: If realloc
isn't allowed for trivially copyable types (that is, all copy and move constructors and assignment operators are trivial, there is at least one copy or move constructor or assignment operator, and the destructor is trivial), this seems like a bug in the standard I can't imagine a compiler writer causing issues here.
Language lawyer answer: I don't think this is allowed by the standard for any type other than char
, unsigned char
, and std::byte
, and I'm no longer as certain about those as I was when I commented to the question (it would be fine if there were some underlying object created by realloc
, but there isn't). These functions are specified to "have the semantics specified in the C standard library", which isn't particularly helpful because C doesn't have a semantic equivalent to the C++ concept of "object". The general understanding of malloc
is that it does not create a C++ object, so you need to do that yourself with placement new
; I would assume the same happens for realloc
.
Your proposed solution of using placement new[]
on the result of realloc
would also not work. Because new[]
needs to keep track of the number of elements allocated (for use by delete[]
), it is allowed to add some overhead space, and then return a pointer later than the one it received so the first part is the overhead. Although this isn't necessary with placement new[]
, it is still allowed (which makes me think there is no valid way to use placement new[]
at all because you don't know how much overhead will be requested, so can't be sure you have enough space for it).
Even if you ensured you only used non-array placement new
(I can think of a couple workarounds where realloc
still makes sense), it would indeed create a valid object there (for types with trivial default constructors, which are at least allowed to do no work when default-initialized), but it might have indeterminate value. Right now it seems to me that it probably works but the standard is somewhat ambiguous, but that is debatable and I may be wrong.