autox1={1,2};// decltype(x1) is std::initializer_list<int> autox2={1,2.0};// error: cannot deduce element typeautox3{1,2};// error: not a single elementautox4={3};// decltype(x4) is std::initializer_list<int>autox5{3};// decltype(x5) is int
#include<array>// Chapter Clarification/copy_elision_non_moveable.cpp #include <array>// based on P0135R0structNonMoveable{NonMoveable(intx):v(x){}NonMoveable(constNonMoveable&)=delete;NonMoveable(NonMoveable&&)=delete;std::array<int,1024>arr;intv;};NonMoveablemake(intval){if(val>0)returnNonMoveable(val);returnNonMoveable(-val);}intmain(){autolargeNonMoveableObj=make(90);returnlargeNonMoveableObj.v;}
template<typenameT=float>structMyContainer{Tval;MyContainer():val(){}MyContainer(Tval):val(val){}// ...};MyContainerc1{1};// OK MyContainer<int>MyContainerc2;// OK MyContainer<float>
折叠表达式
一元右折叠 (E op ...) 成为 (E1 op (... op (EN-1 op EN)))
一元左折叠 (... op E) 成为 (((E1 op E2) op ...) op EN)
二元右折叠 (E op ... op I) 成为 (E1 op (... op (EN−1 op (EN op I))))
二元左折叠 (I op ... op E) 成为 ((((I op E1) op E2) op ...) op EN)
列表初始化自动推导
1234
autox1{1,2,3};// error: not a single elementautox2={1,2,3};// decltype(x2) is std::initializer_list<int>autox3{3};// decltype(x3) is intautox4{3.0};// decltype(x4) is double
Lambda通过值语义拷贝this
这个在C++17之前是做不到的,只能传引用,或者指针拷贝
1 2 3 4 5 6 7 8 910111213141516
structMyObj{intvalue{123};// this 指针拷贝autogetValueCopy(){return[*this]{returnvalue;};}autogetValueRef(){return[this]{returnvalue;};}};MyObjmo;autovalueCopy=mo.getValueCopy();autovalueRef=mo.getValueRef();mo.value=321;valueCopy();// 123valueRef();// 321
std::optional<std::string>create(boolb){if(b){return"Godzilla";}else{return{};}}create(false).value_or("empty");// == "empty"create(true).value();// == "Godzilla"// optional-returning factory functions are usable as conditions of while and ifif(autostr=create(true)){// ...}
std::map<int,string>src{{1,"one"},{2,"two"},{3,"buckle my shoe"}};std::map<int,string>dst{{3,"three"}};dst.insert(src.extract(src.find(1)));// Cheap remove and insert of { 1, "one" } from `src` to `dst`.dst.insert(src.extract(2));// Cheap remove and insert of { 2, "two" } from `src` to `dst`.// dst == { { 1, "one" }, { 2, "two" }, { 3, "three" } };
std::filesystem
std::byte
并行算法
C++14
Lambda capture initializers
通过捕获表达式初始化可以
1 2 3 4 5 6 7 8 910
intfactory(inti){returni*10;}autof=[x=factory(2)]{returnx;};// returns 20autogenerator=[x=0]()mutable{// this would not compile without 'mutable' as we are modifying x on each callreturnx++;};autoa=generator();// == 0autob=generator();// == 1autoc=generator();// == 2
借助捕获表达式初始化来完成变量move到lambda中
12345678
autop=std::make_unique<int>(1);// 没办法拷贝autotask1=[=]{*p=5;};// ERROR: std::unique_ptr cannot be copied// vs.// move进去autotask2=[p=std::move(p)]{*p=5;};// OK: p is move-constructed into the closure object// the original p is empty after task2 is created