我static
对成员的类内初始化有点困惑const
。例如,在下面的代码中:
#include <iostream>
struct Foo
{
const static int n = 42;
};
// const int Foo::n; // No ODR
void f(const int& param)
{
std::cout << param << std::endl;
}
int g(const int& param)
{
return param;
}
template<int N>
void h()
{
std::cout << N << std::endl;
}
int main()
{
// f(Foo::n); // linker error, both g++/clang++
std::cout << g(Foo::n) << std::endl; // OK in g++ only with -O(1,2 or 3) flag, why?!
h<Foo::n>(); // this should be fine
}
我没有定义Foo::n
(该行已注释)。所以,我希望调用f(Foo::n)
在链接时失败,确实如此。但是,std::cout << g(Foo::n) << std::endl;
每当我使用优化标志(例如-O1/2/3
.
- 为什么打开优化时gcc(用 gcc5.2.0 和 gcc 4.9.3 尝试过)编译和链接代码?
- 我是否正确地说类内静态 const 成员的唯一用法是常量表达式,例如
h<Foo::n>
调用中的模板参数,在这种情况下代码应该链接?