[TOC] # decltype ``` int x = 0; decltype(x) y = x; decltype(0) i = 0; std::vecter<decltype(0)> v; decltype(v)::iterator iter; ``` # std::ref和std::cref # 移动语义和拷贝构造 ``` template<typename T> void print(T &t) { std::cout << "lvalue\n"; } template<typename T> void print(T &&t) { std::cout << "rvalue\n"; } template<typename T> void forward(T &&t) { print(std::forward<T>(t)); } void testRValue() { int *x = 0; print(x); //lvalue print(9); //rvalue print("lsy");//lvalue print('1');//rvalue print(std::move(x));//rvalue } ``` # auto func(...)->type {...} ``` auto func(int x) -> decltype(x) { std::cout << x << std::endl; return x; } template<typename T,typename U> auto func(const T &t, const U &u) -> decltype(t + u) { return t + u; } void testFunc() { func(1); std::cout<<func(1, 1.2)<<std::endl; } ``` # default 缺省的构造/虚构等特殊的成员函数,不仅明确代码,而且更好让编译器优化。 # delete 禁用某些函数,通常使用在构造函数和拷贝构造函数,阻止对象拷贝(在C++11前可以使用私有化方式) # override - 避免重写非virtual函数 - 避免重写函数声明错误 # 初始化 ``` int i{1}; double d{1.}; std::vector<int> v{1,2,3,4}; ``` # 委托构造 ``` class demo { public: demo():demo(0,0){} demo(int a):demo(a,0){} demo(int a,int b):x(a),y(b){} private: int x; int y; }; ``` # 类型别名 ``` using int64 = long; using llong = long long; template<typename T> using demo_long = demo<T,long>; demo_long<char> d; ``` # nullptr 使用nullptr而不是NULL,NULL作为 # final - 类名后:禁止被继承 - 虚函数后:禁止被重写 # constexpr编译器常量 ``` const int k = 1; constexpr int kk = 2; constexpr long demo() { return 100*100; } ``` # static_assert静态断言 assert无法用于检测反省编程的错误。 # lambda ``` [capture(=:copy,&:ref,var:copy)](Args...){dosomething;} for_each(v.begin(),v.end(),[](int x){ std::cout << x; }); ``` # 泛型lambda ``` auto f = [](auto x){}; ``` # 并发 ``` extern x; // 为外部变量 static y = 0 //为静态变量,本文件访问 thread_local x = 0 //为线程局部变量,每个线程一份 auto f = [&](){++x,++y;cout<<x<<":"<<y<<endl;}; thread t1(f); thread t2(f); t1.join();t2.join(); cout << x << ":" << y << endl; //结果 1:1 2:1 2:0 ``` # 五异常保证 c++11/14已经弃用异常 ``` void func noexcept { } ``` # 内联namespace 如果多个开发版本,方便release其中一个版本 ``` namespace release { namespace v001 { void func(){} } inline namespace v002 { void func(){} } } void test() { release::v001::func(); releade::func(); } ``` # 强类型enum ``` enum class color { red,green,blue }; auto x = color::red; auto y = red; // error auto z = color::red + 1;//不能隐式转换为int ``` # deprecated 被弃用 ``` class[[deprecated]] demo{}; //类被弃用 void [[deprecated]]testDecltype() noexcept { [[deprecated]]std::vector<decltype(0)> v; v.push_back(0); std::cout << "fff" << std::endl; } ``` # __cplusplus ``` # define ____cplusplus c++版本 ``` # 原始字符串 ``` string s = R"(this is a "\string\")"; cout << s << endl; 输出: this is a "\string\" ``` # 自定义字面值 ``` using uint64 = unsigned long long; long operator"" kb(uint64 v) { return v * 1024; } void testLiteral() { uint64 x = 2kb; std::cout << x << std::endl; } ``` # 二进制字面值 - `0b/2B`代表二进制数据