gpt4 book ai didi

c++ - constexpr int* ptr =&i 在 msvc 中编译但不使用 clang 和 gcc

转载 作者:行者123 更新时间:2023-12-05 04:22:05 25 4
gpt4 key购买 nike

我正在使用列出的书籍学习 constexpr 变量 here .特别是我在 C++ Primer 中读到:

Variables declared constexpr are implicitly const and must be initialized with constant expressions.

现在,为了进一步理清我的概念并检查我是否理解正确,我编写了以下使用 msvc 而不是 gcc 和 clang 编译的简单程序: Demo

int main(void)
{
int i = 0;
constexpr int *ptr= &i; //compiles with msvc but not with clang and gcc
}

那么,我的问题是哪个编译器就在这里(如果有的话)?

最佳答案

程序格式错误msvc 在接受代码时出错。这是因为 i 不是静态分配的对象,因此它的地址不是常量。基本上,因为我们只能从 nullptr 字面量或字面量 0从一个对象的地址初始化一个 constexpr 指针具有固定地址,在您的示例中,i 不是具有固定地址的对象,因此 &i 不是常量表达式.

这个可以从expr.const#11看出来其中指出:

A constant expression is either a glvalue core constant expression that refers to an entity that is a permitted result of a constant expression (as defined below), or a prvalue core constant expression whose value satisfies the following constraints:

  • if the value is of pointer type, it contains the address of an object with static storage duration, the address past the end of such an object ([expr.add]), the address of a non-immediate function, or a null pointer value,

An entity is a permitted result of a constant expression if it is an object with static storage duration that either is not a temporary object or is a temporary object whose value satisfies the above constraints, or if it is a non-immediate function.

(强调我的)

这意味着有两种方法可以解决这个问题。 首先 是您可以在i 前面添加static 使其成为本地静态。 第二个 是将i 的定义移动到main 函数之外的全局范围。在这两种情况下(如下所示),i 将具有静态存储持续时间,因此 &i 现在将是根据上面引用的常量表达式声明。


方法一

int main()
{
//-vvvvvv------------->static added here so that i now has static storage duration
static int i = 0;
constexpr int *ptr= &i; //works now

}

方法二

int i = 0;  //make i global so that i now has static storage duration  
int main()
{

constexpr int *ptr= &i; //works now
}

这是 msvc 错误报告:

MSVC compiles invalid constexpr int*ptr= &i where i is a local nonstatic object

关于c++ - constexpr int* ptr =&i 在 msvc 中编译但不使用 clang 和 gcc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74080638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com