Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The object representation of an object of type T is the sequence of N unsigned char objects taken up by the object of type T, where N equals sizeof(T). The value representation of an object is the set of bits that hold the value of type T.

Some typestypes—for example, such as integral types like such as int and wchar_t, have —have an object representation comprised composed solely of the bits from the object's value representation. For such types, accessing any of the bits of the value representation is well-defined behavior. This form of object representation allows a programmer to use byte-wise access of the object, such as by calling std::memcmp() on it's its object representation. Other types, such as classes, may not have an object representation comprised composed solely of the bits from the object's value representation. For instance, classes may have bitfield bit-field data members, padding inserted between data members, a vtable to support virtual method dispatch, or have data members declared with different access privileges. For such types, accessing bits of the object representation that are not part of the object's value representation may result in undefined behavior depending on how those bits are accessed.

...

In this compliant solution, S overloads operator==() to perform a comparison of the value representation of the object.:

Code Block
bgColor#ccccff
langcpp
struct S {  
  unsigned char buff_type;
  int size;
 
  friend bool operator==(const S &LHS, const S &RHS) {
    return LHS.buff_type == RHS.buff_type &&
           LHS.size == RHS.size;
  }
};
 
void f(const S &s1, const S &s2) {
  if (s1 == s2) {
    // ...
  }
}

...

EXP62-CPP-EX1: It is permissible to access the bits of an object representation when that access is otherwise unobservable in well-defined code. For instance, it is acceptable to call std::memcpy() on an object containing a bit-field, as in the following example, because the read and write of the padding bits cannot be observed. However, the code still must still comply with OOP57-CPP. Prefer special member functions and overloaded operators to C Standard Library functions.

...

[ISO/IEC 14882-2014]Subclause 3.9, "Types"
Subclause 3.10, "Lvalues and Rvalues"
Clause 9, "Classes" 

 

...

Image Modified  Image Modified