为什么不是来自常量POD对象常量的字段本身?

Bru*_*nez 3 c++ templates

我想专门为某个GUID模板,这是一个16字节的结构.GUID对象具有内部链接,因此我不能使用对象本身的地址,但我认为我可以使用对象的内容,因为对象是常量.但这不起作用,如此示例代码所示:

struct S
{
    int const i;
};
S const s = { 42 };
char arr[s.i];
Run Code Online (Sandbox Code Playgroud)

如果s是,为什么不是常数?任何解决方法?

Rya*_*ing 7

struct的初始化s可以在运行时发生.但是,必须在编译时知道数组的大小.编译器不会(肯定地)知道s.i在编译时已知的值,所以它只是看到你正在使用变量来做你不应该做的事情.问题不在于constness,而是需要数组大小的问题.

你可能误解了什么const意思.它只意味着在变量初始化之后,它永远不会改变.例如,这是合法的:

void func(int x){
    const int i = x*5; //can't be known at compile-time, but still const
    //int array[i]; //<-- this would be illegal even though i is const 
}

int main(){
    int i;
    std::cin >> i;
    func(i);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为了解决这个限制,在C++ 11中,您可以将其标记为constexpr表示可以在编译时确定该值.这似乎是你想要的.

struct S
{
    int const i;
};
int main(){
    constexpr S const s = { 42 };
    char arr[s.i];
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译:

$ c++ -std=c++11 -pedantic file.cpp


在C99中,你所做的是合法的,在编译时不需要知道数组的大小.

struct S
{
    int const i;
};
int main(){
    struct S const s = { 42 };
    char arr[s.i];
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译:

$ cc -std=c99 -pedantic file.c