Search code examples
c++referenceconstantslanguage-lawyerside-effects

Can C++ compiler assume a const bool & value will not change?


Can the C++ compiler assume a 'const bool &' value will not change?

For example, imagine that I have a class:

class test {
public:
  test(const bool &state)
    : _test(state) {
  }

  void doSomething() {
    if (_test) {
      doMore();
    }
  }
  void doMore();

private:
  const bool &_test;
};

And I use it as follows:

void example() {
  bool myState = true;
  test myTest(myState);

  while (someTest()) {
    myTest.doSomething();
    myState = anotherTest();
  }
}

Is it allowed by the standard for the compiler to assume _test's value will not change.

I think not, but just want to be certain.


Solution

  • No. Just because your reference (or pointer) is a const does not stop someone else from having a non-const reference. Like this:

    int main(void) {
      bool myState = true;
      test myTest(myState);
      std::cout << myTest.getState() << std::endl;
      myState = false;
      std::cout << myTest.getState() << std::endl;
    }
    

    Or even more simply:

    bool a = true;
    const bool& b = a;
    a = false; // OK
    b = true; // error: assignment of read-only reference ‘b’