C++编译器可以假设const bool&value不会改变吗?

Wil*_*mKF 5 c++ const reference side-effects language-lawyer

C++编译器可以假设'const bool&'值不会改变吗?

例如,假设我有一个类:

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

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

private:
  const bool &_test;
};
Run Code Online (Sandbox Code Playgroud)

我用它如下:

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

  while (someTest()) {
    myTest.doSomething();
    myState = anotherTest();
  }
}
Run Code Online (Sandbox Code Playgroud)

是否允许编译器的标准假设_test的值不会改变.

我想不是,但只是想确定.

Jos*_*Lee 7

不.仅仅因为您的引用(或指针)是一个const并不会阻止其他人进行非const引用.像这样:

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

甚至更简单:

bool a = true;
const bool& b = a;
a = false; // OK
b = true; // error: assignment of read-only reference ‘b’
Run Code Online (Sandbox Code Playgroud)


Aas*_*set 5

const Type & r意味着" 不能通过对它的引用来r改变它的值 " - 但它可能会被直接访问引用值的其他代码(或通过非const引用或指针)改变.同样适用于const Type * p:" p指向的值不能通过指向它的指针来改变.