I know that trivially copyable objects can safely be copied my malloc
into an appropriate storage location1 and that the destination object will have the same value as the source.
Is this also possible with realloc
? That is, if realloc
some storage containing some objects of type T
, and realloc
decides to move and copy the block, will the objects in the newly allocated storage be intact and have started their lifetime, and will the lifetime of the objects in the old storage be safely ended?
1 While asking this question, I had assumed that an "appropriate storage location" included uninitialized storage of suitable alignment and size, but as M.M's answer below argues this isn't actually well supported by the standard. That would make realloc
questionable since it is always copying into uninitialized storage.
malloc
,calloc
,realloc
andfree
in the first place - just avoid having to ask the question. C++ has better alternatives in all cases - use them. – SewardT
, ... the underlying bytes (1.7) making up the object can be copied into an array of char or unsigned char. If the content of the array of char or unsigned char is copied back into the object, the object shall subsequently hold its original value." Emphasis mine. That's not what happens withrealloc
– Uzbek[basic.types]/3
rather than/2
that is generally understood to provide the copying guarantee. Unless your claim is that trivially copyable types cannot be copied bymemcpy
? It's widely understood that they can and the feature is heavily used. – Pacificallymemcpy
specifically. The footnote says "By using, for example, the library functions (17.6.1.2)std::memcpy
orstd::memmove
"realloc
copies the underlying bytes - I don't see why this is not good enough. – Uzbek