constexpr initializing with pointers(constexpr 用指针初始化)
问题描述
我正在尝试使用指向 int 的指针初始化 constexpr 声明,该指针是一个 const 对象.我也尝试用非 const 类型的对象来定义对象.
I am trying to initialize a constexpr declaration with a pointer to int which is a const object. I also try to define an object with a object that is not a const type.
代码:
#include <iostream>
int main()
{
constexpr int *np = nullptr; // np is a constant to int that points to null;
int j = 0;
constexpr int i = 42; // type of i is const int
constexpr const int *p = &i; // p is a constant pointer to the const int i;
constexpr int *p1 = &j; // p1 is a constant pointer to the int j;
}
g++ 日志:
constexpr.cc:8:27: error: ‘& i’ is not a constant expression
constexpr.cc:9:22: error: ‘& j’ is not a constant expression
我相信这是因为 main 中的对象没有固定地址,因此 g++ 正在向我抛出错误消息;我将如何纠正这个?不使用文字类型.
I believe it is because the objects in main have no fixed addresses, thus g++ is throwing error messages back at me; how would I correct this? Without using literal types.
推荐答案
让它们static
来固定它们的地址:
Make them static
to fix their addresses:
int main()
{
constexpr int *np = nullptr; // np is a constant to int that points to null;
static int j = 0;
static constexpr int i = 42; // type of i is const int
constexpr const int *p = &i; // p is a constant pointer to the const int i;
constexpr int *p1 = &j; // p1 is a constant pointer to the int j;
}
这被称为地址常量表达式 [5.19p3]:
This is known as an address constant expression [5.19p3]:
地址常量表达式是prvalue核心常量表达式指针类型,计算为静态对象的地址存储持续时间、函数地址或空指针value 或 std::nullptr_t 类型的纯右值核心常量表达式.
An address constant expression is a prvalue core constant expression of pointer type that evaluates to the address of an object with static storage duration, to the address of a function, or to a null pointer value, or a prvalue core constant expression of type std::nullptr_t.
这篇关于constexpr 用指针初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:constexpr 用指针初始化


基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01