C++11以上的新特性整理

1、nullptr

void foo(char *); 
void foo(int);
foo(NULL) //编译出错,不知道调用哪个,可能调用了foo(int)
foo(nullptr) //ok ,调用foo(char*)
//用nullptr替换原先的NULL

2、constexpr

#define LEN 10

int len_foo() {
    return 5;
}

int main() {
    char arr_1[10];
    char arr_2[LEN];
    int len = 5;
    char arr_3[len+5];          // 非法
    const int len_2 = 10;
    char arr_4[len_2+5];        // 合法
    char arr_5[len_foo()+5];  // 非法

    return 0;
}

改成:constexpr int len_foo() {
    return 5;
}
constexpr int len = 5;

 3、auto 与 decltype用于类型推导

// 由于 cbegin() 将返回 vector<int>::const_iterator 
// 所以 itr 也应该是 vector<int>::const_iterator 类型
for(auto itr = vec.cbegin(); itr != vec.cend(); ++itr);

auto x = 1; auto y = 2; decltype(x+y) z;

4、基于范围的for循环

int array[] = {1,2,3,4,5};
for(auto &x : array) {
    std::cout << x << std::endl;
}

5、using的新用法,using可以替换typedef,可读性更好,也更灵活

template <typename T,typename U,int value>
class SuckType
{
public:
    T a;
    U b;
    SuckType():a(value),b(value){}
};

template <typename U>
using NewType = SuckType<int, U, 1>;     //typedef不支持模板推导  
using Process = int(*)(void*);           // 等效于 typedef int(*Process)(void*);

 待添加----------------------------------------------------------------------------------------

猜你喜欢

转载自www.cnblogs.com/xuhuajie/p/9917175.html
今日推荐