为什么下面的工作原理gcc却没有clang,(现场观看):
constexpr int giveMeValue() { return 42; }
struct TryMe {
static constexpr int arr[1] = {
giveMeValue()
};
};
int main() {
int val = TryMe::arr[0];
return val;
}
Run Code Online (Sandbox Code Playgroud)
我得到一个未解决的外部符号与clang.
是TryMe::arr[0]一个对象?如果是的话,它是否经常使用?
举个例子:
#include <iostream>
class A
{
public:
static const int numberOfWheels = 4;
};
// const int A::numberOfWheels;
int main()
{
std::cout << A::numberOfWheels << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
难道是正式未定义行为(UB),因为A::numberOfWheels是使用没有它的定义是什么?(另见这里).正如C++ 03所述:
如果在程序中使用该成员,并且名称空间范围定义不包含初始化程序,则该成员仍应在名称空间作用域中定义.
我发现在C++ 03 中使用的定义相当混乱,因为它指向可能被评估的表达式:
如果对象或非重载函数的名称出现在可能已评估的表达式中,则使用该函数.
从我的猜测来看,它排除了以下表达式:
sizeof(A::numberOfWheels) ;
typeid(A::numberOfWheels).name() ;
Run Code Online (Sandbox Code Playgroud)
但不一定是<<像上面那样重载运算符的表达式.