C++11 新特性之 nullptr

对于C和C++程序员来说,一定不会对NULL感到陌生。但是C和C++中的NULL却不等价。NULL表示指针不指向任何对象。

NULL是一个宏定义

在C中将NULL定义为void*指针值为0

#define NULL (void*)0

在C++中,NULL被定义为常数0

#ifndef NULL  
#ifdef __cplusplus  
#define NULL    0  
#else  
#define NULL    ((void *)0)  
#endif  
#endif  

考虑下面的程序

#include <iostream>
#include <typeinfo>
using namespace std;

void f(int i)
{
	cout << "f(int)" << endl;
}

void f(void* ptr)
{
	cout << "f(void*)" << endl;
}

int main()
{
	f(NULL); 
	return 0;
}

输出结果:


nullptr取代了有错误倾向的NULL,nullptr可以被理解为指向NULL的指针

#include <iostream>
#include <typeinfo>
using namespace std;

void f(int i)
{
	cout << "f(int)" << endl;
}

void f(void* ptr)
{
	cout << "f(void*)" << endl;
}

int main()
{
	//f(NULL);
	f(0);       //输出为f(int)
	f(nullptr); //输出为f(void*)
	return 0;
}

nullptr适用于所有指针类别,包括函数指针和成员指针

const char *pc = str.c_str();
if (pc != nullptr)
	cout << pc << endl;
void (*func)() = nullptr;

不能将nullptr赋值给整形

int i1 = nullptr;    //error
if (i1 == nullptr){} //error
if (nullptr){}       //error
nullptr = 0;         //error







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值