问题描述
我要检查dynamic_cast的结果.在c ++ 11(或c ++ 0x,对于支持nullptr的编译器)中,我应该与nullptr或0进行比较吗?
I want to check the result of dynamic_cast. In c++11 (or c++0x, for compilers that support nullptr), should I compare against nullptr or 0?
有关系吗?如果有,为什么?
Does it matter, and if so, why?
结果是否依赖于编译器?
Is the result compiler-dependent?
推荐答案
常量nullptr
(类型为nullptr_t
)和常量0
都将隐式转换为任何指针类型的null值.因此,与任何一个进行比较将是可行的,并且从技术上讲是可以的.顺便说一句,这意味着dynamic_cast
都不返回任何一个,它返回特定指针类型的空值.
Both the constant nullptr
(which is of type nullptr_t
) and the constant 0
will implicitly convert to the null value of any pointer type. So comparing against either one will work and is technically OK. By the way, this means that dynamic_cast
return neither one, it returns the null value for the particular pointer type.
最好是养成使用nullptr
而不是0
的习惯.据我所知,只有真正适当的重载解析才有必要(例如,一个重载占用int
而另一个重载占用char*
).为了保持一致性,最好避免使用0
.
It's probably best to get in the habit of using nullptr
rather than 0
. As far as I know, it's only really necessary for proper overload resolution (e.g. one overload takes int
and another takes char*
). For consistency, avoiding 0
will be best.
指针类型的空值"是什么意思?
考虑变量char * ptr
.它的类型是(毫不奇怪)char *
.但是nullptr
的类型是特殊类型nullptr_t
.因此,当我们编写ptr = nullptr
之类的东西时,必须发生一些技术性的事情
Consider a variable char * ptr
. It's type is (unsurprisingly) char *
. But the type of nullptr
is the special type nullptr_t
. So when we write something like ptr = nullptr
, some technical things must happen
-
nullptr
必须隐式转换为char *
. - 此转换的结果设置为
ptr
的新值.
nullptr
must be implicitly converted tochar *
.- The result of this conversion is set as the new value of
ptr
.
char *
的空值是将nullptr
转换为char *
的结果.从概念上讲,它仍然是nullptr
,但是具有不同的类型(char *
).此空值不同于int *
或string *
的空值或任何其他指针类型.我们倾向于将这些空值视为nullptr
(或0
),但每个值实际上都是与不同类型不同的值. (顺便说一下,使用==
进行比较时也会发生相同的转换).
The null value for char *
is the result of converting nullptr
to char *
. Conceptually, it's still nullptr
, but with a different type (char *
). This null value is distinct from the null value of int *
or string *
or any other pointer type. We tend to think of these null values as just nullptr
(or 0
), but each one is really a distinct value from a different type. (By the way, the same conversion happens for comparison using ==
).
尽管这听起来像是挑剔的细节,但在重载解析中非常重要:
Although this may sound like nitpicking details, it's very important in overload resolution:
void foo(char * ptr) { ... }
void foo(int i) { ... }
void foo(nullptr_t ptr) { ... }
int main()
{
foo(0); // Calls void foo(int), since 0 is an int
foo(nullptr); // Calls void foo(nullptr_t), since nullptr is a nullptr_t
foo(new char('c')); // Calls void foo(char *), since new char('c') is a char*
}
或分配不相关的空值时
char * c_ptr = nullptr; // Okay
int * i_ptr1 = nullptr; // Okay
int * i_ptr2 = c_ptr; // COMPILER ERROR HERE
这篇关于在c ++ 11中,dynamic_cast是否返回nullptr或0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!