简体   繁体   English

“int * ptr = int()”值初始化如何不违法?

[英]How is “int* ptr = int()” value initialization not illegal?

The following code (taken from here ): 以下代码(取自此处 ):

int* ptr = int();

compiles in Visual C++ and value-initializes the pointer. 在Visual C ++中编译并对指针进行值初始化。

How is that possible? 怎么可能? I mean int() yields an object of type int and I can't assign an int to a pointer. 我的意思是int()产生一个int类型的对象,我不能将int赋给指针。

How is the code above not illegal? 上面的代码如何不违法?

int() is a constant expression with a value of 0, so it's a valid way of producing a null pointer constant. int()是一个值为0的常量表达式,因此它是生成空指针常量的有效方法。 Ultimately, it's just a slightly different way of saying int *ptr = NULL; 最终,这只是一种稍微不同的说法,即int *ptr = NULL;

Because int() yields 0 , which is interchangeable with NULL . 因为int()产生0 ,它可以与NULL互换。 NULL itself is defined as 0 , unlike C's NULL which is (void *) 0 . NULL本身被定义为0 ,不像C的NULL(void *) 0

Note that this would be an error: 请注意,这将是一个错误:

int* ptr = int(5);

and this will still work: 这仍然有效:

int* ptr = int(0);

0 is a special constant value and as such it can be treated as a pointer value. 0是一个特殊的常量值,因此它可以被视为指针值。 Constant expressions that yield 0 , such as 1 - 1 are as well allowed as null-pointer constants. 产生0常量表达式(例如1 - 1也允许作为空指针常量。

表达式int()计算为一个常量的默认初始化整数,即值0.该值是特殊的:它用于初始化指向NULL状态的指针。

From n3290 (C++03 uses similar text), 4.10 Pointer conversions [conv.ptr] paragraph 1 (the emphasis is mine): 从n3290(C ++ 03使用类似文本),4.10指针转换[conv.ptr]第1段(重点是我的):

1 A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zero or a prvalue of type std::nullptr_t. 1空指针常量是整数类型的整数常量表达式(5.19)prvalue,其计算结果为零或类型为std :: nullptr_t的prvalue。 A null pointer constant can be converted to a pointer type; 空指针常量可以转换为指针类型; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type. 结果是该类型的空指针值,并且可以与对象指针或函数指针类型的每个其他值区分开。 Such a conversion is called a null pointer conversion. 这种转换称为空指针转换。 [...] [...]

int() is such an integral constant expression prvalue of integer type that evaluates to zero (that's a mouthful!), and thus can be used to initialize a pointer type. int()是一个整数类型的整数常量表达式prvalue,它的计算结果为零(这是一个满口!),因此可用于初始化指针类型。 As you can see, 0 is not the only integral expression that is special cased. 如您所见, 0不是唯一的特殊表达式的积分表达式。

Well int isn't an object. 井int不是一个对象。

I beleive what's happening here is you're telling the int* to point to some memory address determined by int() 我相信这里发生的事情是你告诉int *指向一个由int()确定的内存地址

so if int() creates 0, int* will point to memory address 0 所以如果int()创建0,则int *将指向内存地址0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM