问题
As far as I am aware, memcpy
into uninitialized storage cannot safely be used to create an copy of the source object.
However, in this thread from last year on the open-std WG21 "ub" list, a participant refers to the new memcpy lifetime-initiation rules:
This doesn’t seem to rise to the level of a bug report, but it might be relevant to the new memcpy lifetime-initiation rules. Will they ascribe some static type to the source and destination bytes?
Based on the context of the question and small amount of type-erasure example code, it appears that it may be related to creating new objects in aligned_storage
via memcpy
.
Search as I might, I can't find a reference to the new rules. I'm particularly curious if they only apply to replacing the contents of an already created object, or if they change the situation around the potential creation of an object in uninitialized memory.
回答1:
The wording has changed a bit, but the general idea remains the same. From intro.object:
An object is created by a definition, by a new-expression, when implicitly changing the active member of a union, or when a temporary object is created ([conv.rval], [class.temporary]).
Those are the only four ways to create an object in C++. memcpy
does not fall into any of those four conditions and hence it does not now (and never has before) create lifetime (implicitly changing the active member of a union can be done via = only, not via memcpy
).
The quote refers to a hypothetical future change to the standard that would bless memcpy
with such ability in certain situations. There was a very long thread on the subject earlier in the year as well.
来源:https://stackoverflow.com/questions/46840853/what-are-the-changes-if-any-to-the-memcpy-lifetime-initalization-rules-in-the