基类成员何时被视为隐藏?Clang与GCC/MSVC编译分歧解析
关于C++中类成员隐藏时机的编译器分歧问题
Clang拒绝编译以下程序:
struct g { static constexpr bool b = true; }; struct h : g { static constexpr bool b = b; }; // clang 报错,gcc、msvc 通过 static_assert(h::b);
我的理解是Clang尝试用b自身初始化该变量,但由于b尚未初始化,读取它会导致未定义行为,而这在常量表达式中是不被允许的。
然而GCC和MSVC均接受该程序,这表明它们直接从基类成员g::b解析h::b的初始化值。这引出了问题:h::b何时开始隐藏其基类成员g::b?
当然,限定b的作用域可以完全解决这种分歧,但这并非本次问题的关注点。
Clang的错误信息:
<source>:2:38: error: constexpr variable 'b' must be initialized by a constant expression 2 | struct h : g { static constexpr bool b = b; }; | ^ ~ <source>:2:42: note: read of object outside its lifetime is not allowed in a constant expression 2 | struct h : g { static constexpr bool b = b; }; | ^
内容的提问来源于stack exchange,提问作者303
相关产品推荐
相关产品推荐

