c++ - 寻找初始化为 const int 和 int 的指针的解释

标签 c++ pointers initialization constants constexpr

我正在通过 C++ Primer 中的练习进行练习,并找到了练习 2.32 的在线解决方案。
我知道以下代码是非法的,因为初始化无法从 int 转换为 int*:int null = 0, *p = null;但是,提到的两个解决方案是我没有提出的:

    const int null3 = 0, *p3 = null3;
    
    constexpr int null4 = 0, *p4 = null4;
为什么在编译期间允许这些没有错误?我仍然期待 p3 和 p4 的初始化需要 & 来表示地址 (&null3, &null4)。
这是我的记事本文件中的代码:

#include <iostream>

int main()
{

//  int null = 0, *p = null; // it is not legal; depending on intent there are two ways to fix (that I can think off atm)

    {
    int null = 0, *p = &null; // if the goal is to point to 'null'
    }
    {
    int null2 = 0, *p2 = 0; // if the goal is to create a nullptr
    }
    {
    const int null3 = 0, *p3 = null3; // if the goal is to create a nullptr
    }
    {
    constexpr int null4 = 0, *p4 = null4; // if the goal is to create a nullptr
    }

return 0;
}
当我通过 Microsoft Visual Studio CMDPrompt 运行时,它允许我'cl "Exercise 2.32.cpp"' 没有错误。

最佳答案

0是表示空指针常量的一种方式。 (它是一个计算结果为零的整数类型。)换句话说,它是一种特殊情况,您可以为其分配一个指针类型。
符合标准的编译器应该针对指针类型分配给 null3 发出诊断信息。和 null4 . (它还应该为 int *p = +0; 发出诊断信息。)如果您没有,则检查是否设置了适当的编译器标志。
使用 nullptr不过要好得多:

int *p = nullptr;

关于c++ - 寻找初始化为 const int 和 int 的指针的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64992425/

相关文章:

c++ - 不向上转换为真正的基类

c - 在嵌入式中取消引用 NULL 指针

c++ - C++ 中的默认结构初始化

C++ 迭代器 : Can iterators to an abstract class be implemented as a nested class?

c++ - 观察者模式 : Why should Subject be Abstract?

c++ - Allegro 5 循环遍历具有相同名称的配置文件值

c++ - 指向具有显式构造函数的对象的指针

c - 在 C 中用 scanf 填充数组(需要打印最后 5 个输入的数字)

c++ - "static functions with block scope are illegal"错误取决于初始化样式?

c++ - 这种初始化语法在即将到来的 c++0x 标准中有效吗?