局部变量的地址是constexpr吗? [英] Is the address of a local variable a constexpr?

查看:96
本文介绍了局部变量的地址是constexpr吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Bjarne Stroustrup's book "The C++ Programming Language (4th Edition)" on p. 267 (Section 10.4.5 Address Constant Expressions), he uses a code example where the address of a local variable is set to a constexpr variable. I thought this looked odd, so I tried running the example with g++ version 7.3.0 and was unable to get the same results. Here is his code example verbatim (although slightly abridged):

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
}

运行此命令时,我得到:

When I run this, I get:

error: ‘(const char*)(& loc)’ is not a constant expression

我不知道g ++发生了什么吗?还是Bjarne的例子还有其他事情?

Is something happening with g++ that I'm not aware of, or is there something more to Bjarne's example?

推荐答案

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

An earlier printing of Bjarne Stroustrup's book "The C++ Programming Language (4th Edition)" on p. 267 has the error outlined in the OP's question. The current printing and electronic copies have been "corrected" but introduced another error described later. It now refers to the following code:

constexpr const char* p1="asdf";

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

This is OK because "asdf" is stored in a fixed memory location. In the earlier printing the book errs here:

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
}

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

However, loc is not in a fixed memory location. it's on the stack and will have varying locations depending on when it is called.

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

However, the current 4th edition printing has another error. This is the code verbatim from 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
}

这是错误的.编译器/链接器确实知道p1的值,并且可以在链接时确定p1+2的值.编译就可以了.

This is wrong. The compiler/linker does know the value of p1 and can determine the value of p1+2 at link time. It compiles just fine.

这篇关于局部变量的地址是constexpr吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆