Better Code: Exploring Validity in C++ - David Sankel - CppCon 2023

Exploring the concept of validity in C++ programming, including the meaning of invalid pointers, meaninglessness of broken objects, and the importance of invariants and language rules.

Key takeaways
  • An invalid pointer is not necessarily bad; it just means we cannot dereference it.
  • Memory that’s not owned by an object and cannot be destroyed or reassigned is equivalent to a broken object, representing meaningless state.
  • Validity also means the object’s state preserves its invariant, i.e. internal invariants and external interactions don’t change its status.
  • In the context of operations on objects, “valid for destruction” and “valid for assignments” refer to whether the object’s final state remains consistent.
  • An object doesn’t need to have a value by default; its value might be determined post-construction or at runtime (e.g., for a hash mapping function).
  • Validity ultimately boils down to ensuring the object or operation preserves its invariants against expected states.
  • The concept “meaningfulness” (or significance) goes beyond mere substantivity (or existence) involving both invariants and external interpretations.
  • There’s a distinction drawn between discardable items, which can be reassigned or demolished without issue, and broken, where it cannot.
  • Essence represents an object’s abstract model, often involving both substance representation and invariant guarantees.
  • Terminology for discussing validly assigned pointers is crucial while programming in C++.
  • Another approach is using the concept of “liveness” or “unbrokeneness, meaning that objects that are operational should be able to continue usage.
  • Validity is not confined to only these two specific scenarios but extends to other more specific scenarios and object types according to specific language rules about value types.
  • Additionally, some code snippets discuss whether it is essential to document objects or invariants, demonstrating potential pitfalls with code comprehension, which leads to misinterpretation or error.
  • As with meaningfulness``discardable`` and valid for destructionvalid with respect to fit means it meets the post-condition specified in the function it belongs to.