vs2012以上版本支持
一. auto的使用:
auto func = less<int>(); //自动表示函数指针
auto ite = vector_a.begin(); //自动表示STL的迭代器
auto p = new foo(); //自动表示变量指针等变量
二. decltype
int x = 3;
decltype(x) y = x; //从变量或表达式中获得类型
三. nullptr区别于NULL
nullptr是为了解决原来C++中NULL的二义性问题而引进的一种新的类型,因为NULL实际上代表的是0
int a = nullptr; // 编译失败,nullptr不能转型为int
四. 简化的for循环,
map<string, int> m{{"a", 1}, {"b", 2}, {"c", 3}};
for (auto p : m){
cout<<p.first<<" : "<<p.second<<endl;
}
五. lambda表达式
vector<int> iv{5, 4, 3, 2, 1};
int a = 2, b = 1;
for_each(iv.begin(), iv.end(), [b](int &x){cout<<(x + b)<<endl;}); //[b]使用外部变量b
for_each(iv.begin(), iv.end(), [=](int &x){x *= (a + b);}); //[=]使用所有外部变量
for_each(iv.begin(), iv.end(), [=](int &x)->int{return x * (a + b);}); //->int返回值是int
auto pos = find_if(iv.begin(), iv.end(), [](int &n)->bool{ return n % 2 == 1; });
auto is_odd = [](int n) {return n % 2 == 1; };
auto pos1 = find_if(iv.begin(), iv.end(), is_odd);
六. 类成员函数覆盖override, final
class A {
public:
virtual void g(int) final { std::cout << "A::g" << std::endl; }
};
class B : public A {
public:
// error C3668: 'B::f' : method with override specifier 'override' did not override any base class methods
virtual void f(short) override { std::cout << "B::f" << std::endl; }
// error C3248: 'A::g': function declared as 'final' cannot be overridden by 'B::g'
virtual void g(int) { std::cout << "A::g" << std::endl; }
};
七. 更好的定义枚举形式
enum class Options { None, One, All };
Options o = Options::All;
八. 智能指针
unique_ptr:不能拷贝, 只能move
auto_ptr: 废弃
九. 编译时断言
static_assert(Size < 3, "Size is too small");
static_assert(std::is_integral<T1>::value, "Type T1 must be integral");
十. 内存转移
std::unique_ptr<int> p2 = std::move(p1);