I have a snippet:
enum class EC {a, b};
struct B {
constexpr B(EC ec): ec_(ec) {}
EC ec_;
};
struct A_base {
constexpr A_base(B b): b_(b) { }
B b_;
};
struct A: A_base {
static constexpr B bbb = EC::a;
constexpr A(B bbbb): A_base(bbbb) { }
};
int main()
{
A a1(A::bbb); // 1
A a2{A::bbb}; // 2
A a3 = A::bbb; // 3
A a4 = {A::bbb}; // 4
}
It compiles good by modern compilers with c++17 support. With c++11 and c++14 standard support linker error occurs. This question was already discussed in Linker error (undefined reference) with `static constexpr const char*` and perfect-forwarding , C++ Linker Error With Class static constexpr and some other discussions. I understand why this error occurs.
However some things I don't understand:
- With clang I always get linker errors. However when I set -O3 optimization or declare a1, a2, a3, a4 variables as constexpr it inlines A::bbb, and there is no error.
- Gcc without optimization needs reference to A::bbb only for a3, and a4. With optimizations and constexpr it behaves exactly like clang.
Is it normal that compilers differ with turned off optimizations and why does gcc treats a1,a2 initializations not equally to a3, a4?