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

Can a 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();
  }
}

Whether the standard for the compiler is allowed to read the value of _test will not change.

I think not, but just want to be sure.

+5
source share
3 answers

No. Just because your link (or pointer) is equal const, does not allow someone else to have a link not const. 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 simpler:

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

const Type & r , " r ", , ( ). const Type * p: ", p, .

+5

, , referand _test doMore, . myState const, () doMore, const . , - -)

In general, it doMorecan call functions that have different pointers / references to the same object by boolanother route. There are no other links in your example, therefore, if the compiler can see all the code that can reference it (including the definition doMore), and none of them changes the value, then it can make an assumption.

+3
source

All Articles