查找指向NULL的指针 [英] Finding a Pointer to NULL

查看:200
本文介绍了查找指向NULL的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有int* foo[SIZE],我想在其中搜索第一个指向NULL的元素.

I have int* foo[SIZE] and I want to search it for the first element that points to NULL.

但是当我这样做时:

 std::find(foo, foo + SIZE, NULL)

我得到了错误:

错误C2446:'==':没有从'const int'到'int *'

error C2446: '==' : no conversion from 'const int' to 'int *'

我应该只使用static_cast<int*>(NULL)而不是NULL吗?

Should I just be using static_cast<int*>(NULL) instead of NULL?

C ++ 11通过 nullptr 解决了这个问题,但是在C ++ 03中这不是我的选择

推荐答案

此问题实际上是在Herb Sutter和Bjarne Stroustrup的研究中发现的:

This problem is actually called out in Herb Sutter and Bjarne Stroustrup's: A name for the null pointer: nullptr:

区分null和零.不能很好地区分null指针和整数0,以解决重载问题.例如,给定两个重载函数f(int)f(char*),调用f(0)明确地解析为f(int).如果不编写显式强制转换(即f((char*)0))或使用命名变量,则无法使用空指针值编写对f(char*)的调用.

Distinguishing between null and zero. The null pointer and an integer 0 cannot be distinguished well for overload resolution. For example, given two overloaded functions f(int) and f(char*), the call f(0) unambiguously resolves to f(int). There is no way to write a call to f(char*) with a null pointer value without writing an explicit cast (i.e., f((char*)0)) or using a named variable

因此,我们看到此问题可以通过以下任一方法解决:

So we see that this problem can be solved by either:

  1. 明确的演员表
  2. 声明具有匹配类型的值,例如:const int* piNULL = NULL

理想情况下,使用显式强制转换时,可以避免使用C-Style强制转换.这些C ++-Style强制转换均有效地返回包含地址NULLint*:

Ideally when using the explicit cast a C-Style cast can be avoided. Either of these C++-Style casts effectively returns an int* containing address NULL:

  • reinterpret_cast<int*>(NULL)
  • static_cast<int*>(NULL)
  • reinterpret_cast<int*>(NULL)
  • static_cast<int*>(NULL)

http://en.cppreference.com/w/cpp/types/NULL 断言:

空指针常量可以隐式转换为任何指针类型;这样的转换导致该类型的空指针值

A null pointer constant may be implicitly converted to any pointer type; such conversion results in the null pointer value of that type

并且由于 static_cast :

使用隐式和用户定义的转换组合在类型之间进行转换

Converts between types using a combination of implicit and user-defined conversions

static_cast reinterpret_cast 其中:

通过重新解释基础位模式在类型之间进行转换

Converts between types by reinterpreting the underlying bit pattern

因此,C ++ 03 static_cast<int*>(NULL)中的是可以实现的C ++ 11 nullptr的最严格的内联定义.

So, in C++03 static_cast<int*>(NULL) is the tightest inline definition of C++11's nullptr that can be achieved.

这篇关于查找指向NULL的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆