可以C ++编译器假设一个const bool&值不会改变? [英] Can C++ compiler assume a const bool & value will not change?
本文介绍了可以C ++编译器假设一个const bool&值不会改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C ++编译器假设const bool&的值不会改变?
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;
};
我使用它如下:
void example() {
bool myState = true;
test myTest(myState);
while (someTest()) {
myTest.doSomething();
myState = anotherTest();
}
}
标准允许编译器假设_test的值不会改变。
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.
推荐答案
否。因为引用(或指针)是 const
不会阻止其他人使用非< - code> const 参考。像这样:
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;
}
或更简单:
bool a = true;
const bool& b = a;
a = false; // OK
b = true; // error: assignment of read-only reference ‘b’
这篇关于可以C ++编译器假设一个const bool&值不会改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文