c++11 std - nullptr

测试代码:

#include 
#include 
#include 
#include 
#include 

using namespace std;

void f(int test);
void f(void* test);

int main(int argc, char *argv[])
{
	f(nullptr);
	f(NULL);
	f(0);
	while(1);
    return EXIT_SUCCESS;
}
void f(int test)
{
    cout<<"int:test = "<

void*:test = 0
int:test = 0
int:test = 0

分析:

在实际应用过程中如果 f 函数 参数是0 或者NULL或被编译器默认的认为是int,如果想调用void f(void* test) 要加强制转换 (void*)0或(void*)NULL可以解决这个问题。

这样就会引起可读性变差,或者忘记加强制性转换直接引入了bug。

为了解决上面的问题C++标准引入了nullptr 关键字,实际上他是一个 const 的 void* 指针,他对任何其他指针复制都会自动强制的转化为对应的指针类型。

你可能感兴趣的:(c++)