Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added an NCCE/CS pair

...

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

Noncompliant Code Example

In this noncompliant code example, std::memset() is used to clear the internal state of an object that is not of a standard-layout type. An implementation may store a vtable within the object instance, which is subsequently overwritten by the call to std::memset(), leading to undefined behavior when virtual method dispatch is required.

Code Block
bgColor#FFCCCC
langcpp
#include <cstring>

struct S {
  int i, j, k;
 
  // ...

  virtual void f();
};

void f() {
  S *s = new S;
  // ...
  std::memset(s, 0, sizeof(S));
  // ...
  s->f();
}

Compliant Solution

In this compliant solution, the data members of S are cleared explicitly instead of calling std::memset():

Code Block
bgColor#ccccff
langcpp
struct S {
  int i, j, k;
 
  // ...

  virtual void f();
  void clear() { i = j = k = 0; }
};

void f() {
  S *s = new S;
  // ...
  s->clear();
  // ...
  s->f();
}

Exceptions

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 comply with OOP57-CPP. Prefer special member functions and overloaded operators to C Standard Library functions.

...