Concerns When Utilizing "memcpy" to Construct Trivially Copyable Objects
In C , the validity of employing "memcpy" to construct objects of trivially copyable types has been a subject of debate. This article explores the nuances and uncertainties surrounding this code:
#include <cstdlib> #include <cstring> struct T // trivially copyable type { int x, y; }; int main() { void *buf = std::malloc( sizeof(T) ); if ( !buf ) return 0; T a{}; std::memcpy(buf, &a, sizeof a); T *b = static_cast<T *>(buf); b->x = b->y; free(buf); }
Uncertain Object Lifetime with "memcpy""
The crux of the question lies in determining whether "*b" represents an object whose lifetime has been initiated and, if so, when this lifetime commences. The C standard remains silent on this matter.
Proposal for Implicit Object Creation and Current Status
To address this ambiguity, proposal p0593 was put forward, advocating for implicit object creation during low-level object manipulation operations such as "malloc" and "memcpy." This proposed change would provide defined behavior for such scenarios. However, this proposal has yet to be officially reviewed.
Guidelines from the Draft C 14 Standard
As per the C 14 draft standard section 1.8 [intro.object], objects are primarily created through definitions, new-expressions, or certain implementation processes. The section 3.9 [basic.types] pertaining to trivially copyable types specifies that copying such objects' bytes is permissible, provided that the values are restored appropriately.
Ongoing Discussion and Alternative Approaches
The "ub mailing list" has facilitated a lively discussion on this topic, focusing on the avoidance of copying through type punning.
Conclusion
The question of "constructing" trivially-copyable objects with "memcpy" remains unresolved within the C standard, leaving room for potential undefined behavior. Ongoing discussions and proposals, such as p0593, aim to clarify and address this issue, bringing greater certainty to low-level object manipulation in C .
The above is the detailed content of Is 'memcpy' a Valid Way to Construct Trivially Copyable Objects in C ?. For more information, please follow other related articles on the PHP Chinese website!