1

C++关于NULL、0、nullptr

 2 years ago
source link: https://forrestsu.github.io/posts/cpp/about-null-0-nullptr/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

C++关于NULL、0、nullptr

2016年7月17日
| 字数 825
| CPP

一 关于NULL、0、nullptr

1 在C语言中NULL被定义为:一个void* 指针,指向的地址为0。

#define NULL ((void *)0)

所以在C语言中我们通常会写出如下语句

int *i = NULL;
foo_t *f = NULL;

2 而在C++中,NULL会被定义为0

#ifndef __cplusplus
#define NULL ((void *)0)
#else   /* C++ */
#define NULL 0
#endif

3 C++11引入了nullptr 来表示空指针

二 在C++中使用NULL的风险

//func1
int mycall(char *a, char *b)
{
    cout<<"char pointer!"<<endl;
}
//func2
int mycall(char *a, int b)
{
    cout<<"int !"<<endl;
}
// func3
int mycall(char *a,nullptr_t nullp)
{
    cout<<"nullptr !"<<endl;
}
int main()
{
    char *a,*b;
    mycall(a,b); //char pointer!
//优先调用func2,没有func2则调用func1或func3;func1和func3同时存在则报错ambiguous
    mycall(a,NULL);//int !
//优先调用func3,没有func3则调用func1,绝不会调用func2。
    mycall(a,nullptr);//nullptr !
    return 0;
}

在写纯C时
(1) 给指针变量赋空指针可以使用NULL

在写C++时
(1) 不要使用NULL, 如果真要使用那就写个0,或者自己定义一个宏 #define iZERO 0
(2) 使用空指针时请用nullptr


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK