我有点困惑static
a 的类内初始化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
}
Live example
我不定义Foo::n
(该行已注释)。所以,我期待着电话f(Foo::n)
在链接时失败,确实如此。但是,下面的行std::cout << g(Foo::n) << std::endl;
每当我使用优化标志(如-O1/2/3
.
- 为什么gcc(尝试过gcc5.2.0和gcc 4.9.3)可以编译and link优化开启时的代码?
- 我这样说对吗?类内静态常量成员的唯一用途是在常量表达式中,例如模板参数
h<Foo::n>
调用,在这种情况下代码应该链接?
我认为编译器在优化期间执行以下操作:
解决方案是在类外部定义变量:
struct Foo
{
const static int n;
};
const int Foo::n = 42;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)