【问题标题】:Looking for Explanation of pointer initializing to const int and int寻找指针初始化为 const int 和 int 的解释
【发布时间】:2021-03-07 14:02:55
【问题描述】:

我正在完成 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"' 没有错误。

【问题讨论】:

  • const int null3 = 0, *p3 = null3; 这仍然给出错误你确定它正在编译吗?
  • 没有错误?我没有找到接受它的编译器:godbolt.org/z/aK1Gvz。你用的是哪个编译器?
  • @D'Kayd:那不应该编译。
  • 绝对是@Bathsheba

标签: c++ pointers initialization constants constexpr


【解决方案1】:

0 是表示空指针常量的一种方式。 (它是一个计算结果为零的整数类型。)换句话说,它是一种特殊情况,您可以为其分配一个指针类型。

一个符合标准的编译器应该对分配给null3null4 的指针类型发出诊断。 (它还应该为int *p = +0; 发出诊断。)如果你的没有,那么检查是否设置了适当的编译器标志。

使用nullptr 会好得多:

int *p = nullptr;

【讨论】:

  • "将指针类型分配给null3" 我总是对此感到困惑,所以这可能是我的英语有限,但不是反过来吗? “将null3 分配给指针”?
  • @idclev463035818:你也可以说。英语就是这样邪恶的。更像是 C++!
  • 在这种情况下我更喜欢 C++
  • 怎么样? AFAIK 文字 0 可用作空指针以在 C++ 中向后兼容,但不能用作值为 0 的常量 int 变量,也不能用作 1 - 1 等常量 int 表达式。
  • 空指针常量的规则在 C++11 中被收紧了;以前的版本允许任何值为 0 的常量表达式右值,因此 + 可以允许使用。
猜你喜欢
  • 1970-01-01
  • 2020-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-19
  • 1970-01-01
  • 2010-11-30
  • 2015-09-10
相关资源
最近更新 更多