1 nullptr and std::nullptr_t
C++11提供了nullptr用来取代0或者NULL。在C++11之前,使用NULL为空指针赋初值,但NULL其实就是0,这时会把NULL当成0来用。如下代码
#include <iostream>
using namespace std;
void f(void*) {
cout << "void*" << endl;
}
void f(int) {
cout << "int" << endl;
}
int main() {
f(NULL); // 如果NULL等于0的话,会调用f(int),我们的本意应该是调用f(void*)。并且如果NULL不为0的话,会导致调用不明确
f(0); // 调用 f(int)
f(nullptr); // 调用 f(void*)
system("pause");
return 0;
}
控制台输出如下
int
int
void*
而nullptr是一个新的关键字,专门表示空指针,它的类型是std::nullptr_t,能隐式转换为任何类型的指针。所以以后在声明一个空指针的时候,建议使用nullptr而不是NULL,这样更明确。
2 auto
在C++11中,我们在声明一个变量或对象,指定它的类型时,可以不使用变量本身的类型而使用auto替代。
auto i = 42; // 编译器根据变量的值来推断变量的类型,i的类型为int
double f();
auto d = f(); // d has type double
虽说auto可以进行变量的推导,但也不能滥用。C++建议在下面两种场景中使用auto
- 变量的类型过长时,如
vector<string> v;
auto pos = v.begin(); // 此时 pos 的类型为 vector<string>::iterator
- 变量的类型太复杂时,如在lambda表达式中
auto l = [](int x)->bool {
};