局部变量的地址是constexpr吗?

joh*_*ell 23 c++ memory-address constexpr c++11

在Bjarne Stroustrup的书“ C ++编程语言(第4版)”中,第110页。267(第10.4.5节“地址常量表达式”)中,他使用了一个代码示例,其中将局部变量的地址设置为constexpr变量。我以为这看起来很奇怪,所以我尝试使用g ++ 7.3.0版运行示例,但无法获得相同的结果。这是他的逐字代码示例(尽管略有删节):

extern char glob;

void f(char loc) {
    constexpr const char* p0 = &glob; // OK: &glob's is a constant
    constexpr const char* p2 = &loc;  // OK: &loc is constant in its scope
}
Run Code Online (Sandbox Code Playgroud)

运行此命令时,我得到:

error: ‘(const char*)(& loc)’ is not a constant expression
Run Code Online (Sandbox Code Playgroud)

g ++发生了我不知道的事情,还是Bjarne的示例有更多事情?

dou*_*oug 17

Bjarne Stroustrup的书“ C ++编程语言(第4版)”的早期印刷在第132页。267在OP的问题中列出了错误。当前的打印和电子副本已被“纠正”,但引入了另一个稍后描述的错误。现在,它引用以下代码:

constexpr const char* p1="asdf";
Run Code Online (Sandbox Code Playgroud)

可以,因为“ asdf”存储在固定的存储位置中。在较早的印刷版本中,书本错误出现在这里:

void f(char loc) {
    constexpr const char* p0 = &glob; // OK: &glob's is a constant
    constexpr const char* p2 = &loc;  // OK: &loc is constant in its scope
}
Run Code Online (Sandbox Code Playgroud)

但是,loc它不在固定的内存位置。它在堆栈中,根据调用时间的不同,位置会有所不同。

但是,当前的第4版印刷还有另一个错误。这是从10.5.4开始的逐字代码:

int main() {
    constexpr const char* p1 = "asdf";
    constexpr const char* p2 = p1;      // OK
    constexpr const char* p3 = p1+2;    // error:  the compiler does not know the value of p1
}
Run Code Online (Sandbox Code Playgroud)

错了 编译器/链接器确实知道p1的值,并且可以确定p1+2链接时的p1值。它编译就好了。

  • 如果它明确指出书中的例子是错误的,那么答案将更加清晰。 (4认同)

joh*_*ell 10

我的“ C ++编程语言(第四版)”的硬拷贝中提供的第10.4.5节中的示例似乎不正确。因此,我得出结论,局部变量的地址不是constexpr

该示例似乎已经在某些pdf版本中进行了更新,如下所示:

在此处输入图片说明