C++11之nullptr
我经常在代码中使用诸如以下代码来给指针变量赋值:
char *buf = NULL;
但是C++11已经摒弃了这种用法。因为这种用法会带来重载解析的麻烦,详见代码:
#include <iostream> using namespace std; void foo(char *); void foo(int); int _tmain(int argc, _TCHAR* argv[]) { if (is_same<decltype(NULL), decltype(0)>::value) { cout << "NULL == 0" << endl; } if (is_same<decltype(NULL), decltype((void*)0)>::value) { cout << "NULL == (void*)0" << endl; } if (is_same<decltype(NULL), nullptr_t>::value) { cout << "NULL == nullptr" << endl; } foo(0); foo(NULL); foo(nullptr); return 0; } void foo(char *) { cout << "foo(char*) is called" << endl; } void foo(int i) { cout << "foo(int) is called" << endl; }
输出结果:
NULL == 0 foo(int) is called foo(int) is called foo(char*) is called