There might be multiple reasons it is unsafe, but a reason it can fail *in practice* is when `simple` is used as a base class, and the derived class stores some of its members in the padding of `simple`. Then, memcpy or memset into a simple object clobbers the derived member.
-
-
Prikaži ovu nit
-
Here's a concrete example: https://godbolt.org/z/7T-fy9 Note how zero_memset does a single 64-bit write to zero the entire object (nice! fast!), but using the idiomatic approach (= T{}) it takes two writes: a 32-bit one for the int and 8-bit for the char, preserving the padding.pic.twitter.com/vK63WyIrY7
Prikaži ovu nit -
Note that simple is all of: "trivial", "trivially copyable", "standard layout" and POD. So if people tell you any of those are enough to do memcpy or memset safely into an object, they are wrong. You additionally need to guarantee it is not a base class object.
Prikaži ovu nit -
One way you might have that guarantee is if you have an array (or array-like) of T (e.g., a T* that must be an array, std::vector<T> or whatever). In that case you know T is the most derived type, so no subobject shenanigans.
Prikaži ovu nit
Kraj razgovora
Novi razgovor -
-
-
Simliar also YIL while watching a talk of H. Hinnant. "Trivial copyable" is usually implmented by copying memberwise which does/should not have this problem. But, sombody in the audience mentioned, there existed old compilers (!) that implemented trivial copyable by bitwise copy.
-
The main point of TC is to enable bitwise copy, if I'm not mistaken? Maybe a secondary point is some kind of optimization around allowing some idioms to be noexcept if the underlying types are TC, I forget. Compilers still regularly do bitwise copy, not just old ones.
- Još 6 drugih odgovora
Novi razgovor -
-
-
Is there a difference between struct and class here? I think there’s a rule about private members that can cause those side effects. Since the compiler expects you to never access these members outside a member function.
-
There is a difference in the sense that if you use struct, the squashing goes away: the size of the classes changes from 8 to 12 and the memset/memcpy is safe (in practice, although not by the language of the standard). That's just because the access control changes - you ...
- Još 13 drugih odgovora
Novi razgovor -
-
-
This isn't some fundamental law of nature we discovered by smashing octets together in a lab at near-C++ velocities! We can make it safe. Change the fucking compilers already.
-
It would be an ABI break, so I don't see it happening (the rules seem not well understood even by compiler writers, because icc is inconsistent here, despite nominally being ABI-compatible). Also, I think people like smaller objects.
- Još 23 druga odgovora
Novi razgovor -
Čini se da učitavanje traje već neko vrijeme.
Twitter je možda preopterećen ili ima kratkotrajnih poteškoća u radu. Pokušajte ponovno ili potražite dodatne informacije u odjeljku Status Twittera.