liveBook · Manning

As-if rule

As explained in Learn C++ by Example

The as-if rule permits a C++ implementation to transform or remove instructions provided the program's observable behavior is unchanged.

The as-if rule lets a C++ implementation transform, reorder, or remove instructions when the program’s observable behavior remains unchanged. section 4.2.4

The rule gives implementations practical freedom while preserving the program’s required behavior:

  • A library type may use any internal representation while behaving as if it followed its documented model. section 4.2.4
  • The compiler may optimize instructions when those changes cannot alter observable behavior. section 4.2.4
  • Undefined behavior removes useful guarantees; reading an uninitialized variable can permit unexpected compiler behavior. section 4.2.4

A clock behaves as if it stores a duration

std::chrono::time_point can behave as if it stores a duration measuring time from a clock’s epoch, even when its actual storage differs. section 4.2.4

std::chrono::time_point now = std::chrono::system_clock::now();

A concrete system_clock call places the as-if discussion in the context of std::chrono::time_point. section 4.2.4

How Learn C++ by Example covers it

How deep it goes
Defines reordering, removal, and alternative storage, then contrasts optimization with undefined behavior.
Examples
Uses time_point, system_clock, duration, epochs, uninitialized variables, and nasal-demons imagery as examples.
What you can do after
Evaluate whether implementations can transform code while preserving observable behavior and recognize undefined behavior as a separate danger.
How it connects
Connects observable behavior, compiler optimization, undefined behavior, time_point, Clock, duration, and epochs.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.