【发布时间】:2020-03-25 19:21:56
【问题描述】:
如果一个类有一个 const 引用数据成员碰巧在该类范围之外发生变化,这是未定义的行为吗?
例如,让我们考虑以下 C++ 代码:
#include <iostream>
class A {
int x;
public:
A(int x): x(x){}
void change(int y){
x = y;
}
friend std::ostream & operator << (std::ostream & os, const A & a){
os << a.x;
return os;
}
};
class B {
const A & a;
public:
B(const A & a) : a(a) {}
friend std::ostream & operator << (std::ostream & os, const B & b){
os << b.a;
return os;
}
};
int main(){
A a(1);
B b(a);
std::cout << a << std::endl;
std::cout << b << std::endl;
a.change(2);
std::cout << a << std::endl;
std::cout << b << std::endl;
}
我的编译器能够正确执行它,并且调试器指出 B::a 的 x 已更改。
感谢您的帮助!
【问题讨论】:
-
const T &并不意味着它指的是T,即const。这意味着它是对T的引用,并且不允许您使用该引用来更改该对象。和const T *是一样的。 -
@FrançoisAndrieux 感谢您的回复!我以为是这样,但由于我刚刚了解了未定义的行为,现在我有一种妄想症,首先要仔细检查所有内容!再次感谢!
-
对 UB 偏执基本上是唯一安全的立场。如果你有任何疑问,确定是正确的。