我们创建一个 nullptr 并在 C++ 的 IF 条件中使用它会发生什么

What happens we create a nullptr and use it in a IF condition in C++

您好,我想看看当我在 C++ 中创建 nullptr 并在 if 语句中使用它时会发生什么。例如,我的代码如下: int *p=nullptr; if(p){cout<<"Inside IF";}

我的问题如下:

  1. 当我们创建一个 nullptr 时会发生什么?我的意思是是否创建了一个新的指针对象来保存值 0(作为地址)或其他值?如果它保存的地址为 0 那么该指针是否指向内存中可能有效的地址?
  2. 当我们在 IF 语句中使用它时会发生什么?我的意思是 IF 语句检查指针对象持有的值是 0 还是其他?

你说的对 nullptr allocates location and gives value 0 and 0 is false in c++

    #include <iostream>
    using namespace std;
    int main() {
    int *p=nullptr; 
    if(p){cout<<"Inside IF";}
    cout<<&p<<endl;
    cout<<p;

     }

输出

0x7ffc92b66710 0

供参考:

int *p=nullptr;

创建一个 int* 指向 int 的指针,具有自动存储持续时间。然后将nullptr赋值给它,并自动转换为int*指针的空指针值。尽管每个指针类型都有从整数文字 0 到空指针值的隐式转换,但该值在内部存储为 0 实际上不一定是这种情况。

然后,在比较

if(p){cout<<"Inside IF";}

从每个指针类型到 bool 都有一个隐式转换,它应用在这个 if 语句中。具体来说:

Boolean conversions

The value zero (for integral, floating-point, and unscoped enumeration) and the null pointer and the null pointer-to-member values become false. All other values become true.

因此 p 具有空 int* 指针的值,因此变为 false.

  1. What happens when we create a nullptr?

您可以创建空指针,但不能创建 nullptr。关键字nullptr表示字面值,不是可以创建的东西。

根据您的代码,您的意思是询问分配指针变量时会发生什么 nullptr。答案是你的变量变成了一个 null pointer,一个不指向任何东西的指针,当在布尔上下文中使用时,它的计算结果为 false

I mean does a new pointer object is created that holds the value 0(as address) or something else?

我们通常认为空指针的值为零,但从技术上讲,实现可以使用具有一些非零位的位模式。只要您不仔细查看编译后的代码,就可以将空指针视为保存地址 0。

And if the address it holds is 0 then is that pointer pointing to a possibly valid address in the memory?

空指针的值必须与所有可能有效的内存地址不同。如果 0 可能是实现中的有效内存地址,则该实现必须使用不同的位模式来表示空指针。 (我不知道有任何实施属于此类。)

  1. What is happening when we use it in the IF statement ?

if 语句的条件是来自指针的 contextually converted to bool. When converting to bool,空指针值转换为 false,所有其他值转换为 true

I mean is the IF statement checking whether the value that the pointer object holds is 0 or something else?

别的东西(但只有细微的意义)。它检查该值是否是空指针值(这在您的计算机上几乎肯定由零位表示,但技术上不能保证如此)。