为什么编译?C++常量在参考上丢失
struct A {};
struct B {
B(A& _a) : a(_a) {}
A &a;
};
void f1(A&) {}
void f2(const B &b) { f1(b.a); }
int main() {
A a;
B b{a};
f2(b);
return 0;
}
f2()b是const,所以我的理解是b.a也应该是const。但它编译并且编译器允许调用f1()。
替换为'A &';'在结构B中用'A a'它不再有效。 现在F1()b.a确实是常量:
invalid initialization of reference of type 'A&' from expression of type 'const A'
请帮我理解这...谢谢。
错误:'const'限定符不能应用于'A&' – Jarek
谁说的? (在什么情况下?)是的,它是[完全多余](https://isocpp.org/wiki/faq/const-correctness#const-ref-nonsense)。无论如何,它更像是思想实验;) –