3 ms·
I agree. It might make sense to use something like memcmp() on structs to assert that they are exactly the same, or to have a dedicated comparison function tha
by mjevans 7y ago
I agree. It might make sense to use something like memcmp() on structs to assert that they are exactly the same, or to have a dedicated comparison function that makes sure they are functionally equivalent for some defined need.
However Objects should have only the second and it might also need to be (I think replacing a function pointer might be) an over-loaded function if something has extended a base object type. I'm not even actually positive that could work if there are two extensions to a base type.
- usrnm 7y ago> It might make sense to use something like memcmp() on structs to assert that they are exactly the same No, actually, it doesn't make sense in general. Due to padding, structs may have arbitrary meaningless bytes between the actual data fields, and memcmp will break on those. It works because structs are often filled with zeroes on initialization, but it isn't required or enforced in any way. I was burnt by this problem more than once, not really fun to debug
- Gibbon1 7y agoFun, create a struct on the stack. Set the elements individually. Padding is now filled with garbage. Any elements you forget to set will also be garbage. When you copy the struct the garbage goes with it. I've been burnt too.
- mjevans 7y agoYou've missed the 'functionally equal' check option; which covers cases like you're focusing on. To check if two differently created things happen to be equal, yes, you should prefer the function that checks exactly what matters exactly how it matters. As you rightly point out, the memcmp check would only work on either pre-zeroed memory (depends on environment and what you're doing) or actual literal copies of a specific struct.
- barrkel 7y agomemcmp() on your structs means any fields of a reference type are back to using reference equality. You need to recurse if you're going to be consistent.
- deleted 7y ago[deleted]