虛擬打印機smartprinter(C 演化及其核心思想與概念)
1 C design aims and strategy
2 C design rules of thumb
3 Early C (1980)
4 C in 2006 (nadir)
5 The standards process
6 C Core guidelines
7 Stability & evolution
8 C 11 – “it feels like a new language”
9 C 20 – “it approximates my D&E aims”
10 C 11 … C 20 Language main feature
11 C 11 example: Range-for, auto, and move
12 Generic programming
13 C in 2020 (the peak so far)
14 Retrospective
15 C 23, C 26, … – we have a plan
1 C design aims and strategy
C 設計的目標和策略
1.1 To improve the state of real-world software
改善現實世界軟件的狀態
– Direct expression of ideas in code
– 在代碼中直接表達想法
– Reliability
– 可靠性
– Performance
– 性能
– Maintainability
– 可維護性
– Development time
– 開發時間
1.2 Start small and grow
從小事做起,不斷成長
– Rely on feedback from real-world use
– 依靠真實世界的使用反饋
– Don’t grow too fast
– 不要發展得過快
1.3 Know roughly where you’d like to go
大致知道你想去哪里
– Or you get lost
– 否則你就會迷失方向
1.4 Rely on articulated principles
依靠明確的原則
– Or you get steamrollered by requests
– 否則你就會被請求壓垮
2 C design rules of thumb
C 設計的經驗法則
A selection from “The Design and Evolution” 1994
1994 年《設計與演化》選錄
– Don’t get involved in a sterile quest for perfection
– 不要陷入對完美的徒勞追求
– Always provide a transition path
– 始終提供過渡路徑
– Say what you mean ①
– 說出你的意圖
i.e., enable direct expression of higher-level ideas
即,能夠直接表達高層次的思路
– Provide as good support for user-defined types as for built-in types ① ②
– 為用戶定義類型提供和內置類型同樣好的支持
– All features must be affordable ③
– 所有的功能都必須是可以負擔得起的
– No implicit violations of the static type system ②
– 不要隱式地在靜態類型系統方面違規
– Preprocessor usage should be eliminated
– 應當取消預處理器的使用
– Leave no room for a lower-level language below C ③
– 不要給C 以下的低級語言留有余地
except assembler
匯編語言除外
① Abstraction 抽象
② Type safety 類型安全,Expressive type system 富于表現力的類型系統
③ Direct use of hardware 直接使用硬件,Zero-overhead abstraction 零開銷抽象
3 Early C (1980)
早期的C (1980)
3.1 abstraction and scope-based resource management
抽象和基于作用域的資源管理
class Vector { // vector of Elements of type double 元素類型為雙精度浮點數的vectorpublic: Vector(int n =0); // constructor: acquire memory for n elements (default: empty) 構造函數:為n 個元素獲取內存(默認:空) ~Vector(); // destructor: destroy elements; release memory …析構函數:銷毀元素;釋放內存private: double* elem; // representation, e.g., pointer to elements plus #elements 表示,例如指向元素的指針以及元素個數 int sz; // #elements 元素個數};void fct(int n){ Vector v (n); … v[0]=1.618; // vector of n doubles; subscripting n 個浮點數的vector; 下標運算 // …} // all memory released here 所有內存在此釋放
Make resource release implicit and guaranteed (RAII)
使資源釋放既是隱式的又有保證(RAII)
All standard-library containers manage their elements
所有標準庫容器都管理其元素
– vector
– list, forward_list (singly-linked list), …
– map, unordered_map (hash table),…
– set, multi_set, …
– string
– …
Resource management pointers handle lifetime of what they point to
資源管理指針處理它們所指向的東西的生存期
– unique_ptr, shared_ptr, …
Some standard-library classes represent non-memory resources
一些標準庫類表示的是非內存資源
– thread, scoped_lock, …
– istream, fstream, …
– …
A container can hold non-memory resources
容器可以容納非內存資源
– This all works recursively
– 這些都可以遞歸地發揮作用
3.2 what really wanted – parameterized types
真正想要的東西—參數化類型
template<class T>class Vector { // vector of Elements of type T 元素類型為T 的vectorpublic: Vector(int n =0); // constructor: acquire memory for n elements (default: empty) 構造函數:為n 個元素獲取內存(默認:空) ~Vector(); // destructor: destroy elements; release memory 析構函數:銷毀元素;釋放內存 // …private: T* elem; // representation, e.g., pointer to elements plus #elements 表示,例如指向元素的指針以及元素個數 int sz; // #elements 元素個數};void fct(int n){ Vector<double> v(n); … v[0]=1.618; // vector of n doubles; subscripting n 個浮點數的vector; 下標運算 Vector<string> vs; … vs.push_back(“Strachey”); // empty vector of strings; grow it 空的字符串vector;增長它 Vector<File_handle> f(3); … f[0] = File_handle(“Myfile”, “r”); // open a file allocate buffers, etc. 打開為文件分配的緩沖區等 // …} // memory, strings, file handles, etc. released here 內存,字符串,文件句柄等在此釋放
4 C in 2006 (nadir) 2006 年的C (低谷)
C was no longer new and exciting
C 不再新奇和令人激動
– 25 years old
– 25 歲了
– About 3 million users (and declining)
– 大約3 百萬用戶(還在減少)
– No major commercial backer
– 沒有主要的商業支持者
– Controlled by a large ISO standards committee
– 被大型ISO 標準化委員會控制
Heavily marketed proprietary languages: Java, C#, …
大肆推廣的專有語言:Java、C#,…
– With massive ecosystems
– 擁有龐大的生態系統
Heavy academic push for alternatives
學術界對替代語言的強力推動
– Massive switch to Java for early programming education
– 早期編程教育大批轉到Java
Single thread hardware performance stalled
單線程硬件性能止步不前
Vastly increased emphasis on energy efficiency
對能效的重視程度大幅提高
Fight for commercial platform dominance
爭奪商業平臺的主導地位
– Java (Sun, IBM, Google), Microsoft (C#), Apple (Objective C)
5 The standards process 標準化流程
Requested by HP, IBM, and Sun in 1989
1989 年由惠普、IBM 和Sun 公司提出要求
– Specifically, an ANSI/ISO standard
– 具體來說,是一套ANSI/ISO 標準
Consensus-based decisions
基于共識的決定
Many national standards bodies
許多國家標準機構
First standard in 1998
第一個標準在1998 年出臺
– Then C 11, C 14, C 17, and C 20
– 然后是C 11、C 14、C 17 和C 20
All unanimously approved after years of work
經過多年的工作,所有的標準都被一致通過
Aims 目標
– Stability
– 穩定性
– Support for wide use
– 支持廣泛使用
– Defense against vendor lock-in
– 防范供應商的鎖定
– Defense against dialects
– 防止方言的出現
– Improvements of language and standard library
– 改進語言和標準庫
Dangers of the ISO standards process
ISO 標準化流程的危險性
– Lack of direction
– 缺少方向
– “Design by committee” – really “design by a federations of committees”
– “由委員會設計”— 實際上是“多委員會的聯合會設計"
– Fossilization
– 僵化
– Delays
– 延遲
– Acceptance of untried ideas
– 接受未經試驗的想法
6 C Core guidelines
C 核心指南
– No resouce leaks
– 沒有資源泄漏
– No memory corruption
– 沒有內存損壞
– No garbage collector
– 不需要垃圾收集器
– No limitation of expressiveness
– 沒表達能力的限制
– No performance degradation
– 沒有性能下降
7 Stability & evolution 穩定性與演化
7.1 How to get both?
如何兼得?
– We can’t simplify the language
– 我們不能簡化語言
Don’t break working code
不要破壞工作的代碼
– We can simplify use
– 我們可以簡化使用
Add improved facilities
增加改進的機制
Offer concrete guidance on how to avoid outdated features
就如何避免過時的特性提供具體的指導
Offer concrete guidance on how to use improvements
為如何使用改進的功能提供具體的指導
7.2 Guidelines need static analysis support to scale
指南需要靜態分析支持來規模化
– Microsoft Visual Studio and (partially) Clang Tidy
– Microsoft Visual Studio和(部分)Clang Tidy
8 C 11 – “it feels like a new language”
C 11 – 感覺像是門新語言
8.1 Support for concurrency 支持并發
– Memory model, lock-free programming, threads and locks, futures, …
– 內存模型,無鎖編程,線程和鎖,期值,...
8.2 Simplify use 簡化使用
– Auto, range-for, move semantics, resource-management pointers, lambdas, uniform initialization, constexpr, user-defined literals, …
– auto、范圍for、移動語義、資源管理指針、lambda 表達式、統一初始化、constexpr、用戶定義字面量,...
8.3 Improve support for generic programming
改進對泛型編程的支持
– Lambdas , variadic templates, template aliases, tuples, constexpr, enum classes,
– Lambda 表達式、變參模板、模板別名、tuple、constexpr、enum class,...
8.4 Increase type safety 提高類型安全
– Type-safe threading and locking, range-for, move semantics, resource-management pointers, user-defined literals, std::array, …
– 類型安全的線程和鎖定、范圍for、移動語義、資源管理指針、用戶定義字面量、std::array, ...
8.5 Improve support for library building
支持對庫的開發
– Lambdas, variadic templates, constexpr, template aliases, tuples, type traits, enable_if, …
– Lambda 表達式、變參模板、constexpr、模板別名、tuple、類型特征、enable_if,...
8.6 Add and improve standard-library components
增加和改進標準庫組件
– threads and locks, regular expressions, time, random numbers, smart pointers, …
– 線程和鎖、正則表達式、時間、隨機數、智能指針,…
9 C 20 – “it approximates my D&E aims”
C 20 – “它接近了我在《設計與演化》中的目標”
9.1 Major language features
主要語言特性
– Modules
– 模塊
– Concepts
– 概念
– Coroutines
– 協程
– Improved compile-time programming support
– 改進的編譯期編程支持
9.2 Major standard-library components
主要標準庫組件
– Ranges
– 范圍
– Dates
– 日期
– Formats
– 格式化
– Parallel algorithms
– 并行算法
– Span
– 跨度
9.3 Many minor language features and standard-library components
許多次要語言特性和標準庫組件
Most shipped by early 2021
大部分到2021 年初已經發布
– In multiple compilers
– 多個編譯器中支持
10 C 11 … C 20 Language main feature
C 11 … C 20 主要語言特性
10.1 Simplify code
簡化代碼
10.2 Move semantics
移動語義
10.3 Improved templates
改進的模板
10.4 Lambdas
lambda 表達式
10.5 Support for compile-time computation
支持編譯期計算
10.6 Generic programming
泛型編程
10.7 Modules
模塊
10.8 Concepts
概念
10.9 Concurrency and parallelism
并發與并行
10.1 Simplify code 簡化代碼
Deduced types
推導出的類型
auto x = 10; // x is an int 是個整型for (auto p = v.begin(); p!=v.end(); p) cout << *p; // p is an iterator 是個迭代器
Range-for
范圍for
for (int x : v) // eliminate loop variable 消除循環變量 cout << x;– for (const auto& x : image_vec) // deduce element type 推導元素類型cout << x;More advanced type deduction
更高級的類型推導
– vector v = { 1,2,3,4,5,6 }; // deduce element type 推導元素類型
– scoped_lock lck { mut } ; // deduce lock type from mutex type 從互斥鎖類型推導鎖類型
Much, much more
還有許多許多
10.2 Move semantics
移動語義
A general mechanism for moving resources
? 移動資源的通用機制
– Completes the C object model
– 完善了C 的對象模型
Safely and cheaply move objects between scopes
在作用域之間安全而廉價地移動對象
No cost and no leaks
沒有成本,也沒有泄漏
– Simplifies code that returns large objects
– 簡化了返回大型對象的代碼
Removes a need for explicit memory management
消除了對顯式內存管理的需要
– Pervasive in the standard library
– 普遍存在于標準庫中
vector<double>* p = compute(); // C 98, old and error-prone: return a pointer C 98,老舊而易錯:返回指針// …delete p; // remember to delete 一定要記得刪除vector<double> x = compute_vec(); // C 11: return a vector; not a pointer C 11:返回vecor;而不是指針
10.3 Improved templates
改進的模板
Variadic templates
變參模板
Safely pass an arbitrary number of arguments of arbitrary types to a function
安全地把任意個任意類型的參數傳給某個函數
template < typename T, typename... Args >void printf ( const char * s, const T& value , const Args &... args ){ while(*s) { if(*s == ‘%’ && * s != ‘%’) { // handle formatting characters 處理格式化字符 std :: cout << value ; // output first/next argument 輸出第一個/下一個實參 return printf ( s, args...); // recursive call 遞歸調用 } std :: cout << *s ; // output ordinary character 輸出普通字符 } throw std :: runtime error (" extra arguments provided to printf ");}printf ( "The value of %s is about %g ( unless you live in %s).n“, msg , std::string (" pi "), 3.14159 , " Indiana ");
Variable templates
變量模板
template<typename T> constexpr T pi_v = T(3.1415926535897932384626433832795028841);constexpr double pi = pi_v<double>;
Alias templates
別名模板
template<typename T> using Vec = vector<T,My_allocator<T>>;Vec<int> vi;
10.4 Lambdas
lambda 表達式
A function object
函數對象
– can carry state and be called as a function
– 能攜帶狀態并當作函數來調用
– can be generic
– 可以是泛型的
– function objects have been used since 1983
– 1983 年以來函數對象就被使用了
– Extremely useful as arguments to algorithms
– 作為算法的實參,極為有用
– Can be blindingly fast (inlining)
– 極其快速(內聯)
A lambda
lambda 表達式
– is a notation for generating a function object
– 是生成函數對象的寫法
– can be created where it’s needed
– 能在需要用它的地方現場創造
sort(v, [](auto& a, auto& b) { return abs(a)>abs(b); });
– can access its environment
– 能訪問它的環境
void f(int x, vector<int>& v){ auto val = find_if(v, [x](auto& a) { return a>x; }); // find an element greater than x 找到一個大于x 的元素 // …}
10.5 Support for compile-time computation
Ordinary functions that can be evaluated at compile time
可以在編譯期求值的普通函數
constexpr int fac(int n) { return n<2 1 : n *fac(n-1); }
Constexper functions are pure
constexpr 函數是純的
– No sideefects
– 沒有副作用
– No access to non-local variables
– 沒有對非局部變量的訪問
– No undefined behavior
– 沒有未定義行為
Steadily generalized over the years
多年來穩步泛化
– Not quite “everything constexpr” (and it shouldn’t be)
– 不完全是“一切皆constexpr”(也不應該是)
constexpr int fact(int n) { int res = 1; while(n>1) res *= n--; return res; }
Not just built-in types
不只是內建類型
– static_assert( weekday{August/25/2021}==Wednesday );
support for compile-time computation
改進對編譯期計算的支持
Make use of abstractions simpler and more affordable
讓抽象的使用更簡單、更能負擔得起
– Traditionally, C Gains performance by moving work from run-time to compile-time
– 傳統上,C 通過將工作從運行期轉移到編譯期來提高性能
Virtual tables, inlining, templates, …
虛表、內聯、模板……
Often eliminates run-time checks and error handlers
通??梢韵\行期的檢查和錯誤處理程序
Help eliminate error-prone practices
有助于消除易出錯的做法
– Macros for computing values
– 用于計算數值的宏
– Macros as a untyped constants
– 作為無類型常量的宏
– Complex template metaprogramming yielding values
– 復雜的模板元編程產生的值
– Magic constants
– 魔法常量
10.6 Generic programming 泛型編程
The backbone of the C standard library
C 標準庫的支柱
Containers and algorithms (“The STL”)
容器與算法(“STL”)
– vector, list, stack, queue, priority_queue, map, unordered_map, ...
– sort(), partial_sort(), is_sorted(), merge(), find(), find_if(),...
– Ranges
– 范圍
Concurrency support (type safe)
并發支持(類型安全)
– Threads, locks, futures, parallel algorithms, ...
– 線程、鎖、期值、并行算法,…
Time 時間
– time_point, duration, calendars (day, month, year), time zones, …
– time_point、duration、日歷(day, month, year)、時區、…
Random numbers 隨機數
– distributions and engines
– 隨機分布和引擎
Numeric types and algorithms
數值類型和算法
– complex, accumulate(), inner_product(), iota(), ...
Strings and Regular expressions
字符串和正則表達式
I/O streams and Formats
I/O 流和格式化
10.7 Modules 模塊
The C header-file model doesn’t offer modularity
C 頭文件模型不提供模塊化
– #include is textual inclusion
– #include 是文本包含
This has been known “forever”
“自古以來”
– Mentioned in D&E
– 在《設計和演化》中提及
– Attempts to remedy
– 嘗試補救
Daveed Vandevoorde (2003-2012)
Doug Gregor (2012)
C 20 design of modules (2009 – 2019)
C 20 中關于模塊的設計(2009-2019)
– Gabriel Dos Reis, Richard Smith, Nathan Sidwell
1 | 2 |
? Order dependence? 依賴于順序#include "a.h"#include "b.h"can be different from可以不同于#include "b.h"#include "a.h"? #include is transitive? #include 是傳遞性的– much repeated compilation– 許多重復的編譯– Subtle bugs– 難以察覺的缺陷 | ? Modularity? 模塊化import a;import b;is same as等同于import b;import a;? import is not transitive? Import 沒有傳遞性– Much compilation can be done onceonly– 大量編譯只需一次完成 |
10.7.1 Modules – Code hygiene 模塊—代碼衛生
? Better code hygiene: modularity (especially protection from macros)
? 更好的代碼衛生:模塊化(尤其防止宏)
export module sequence_printer; // we are defining a module 我們定義一個模塊import iostream; // iostream details not leaked to module user iostream 的細節不會泄露給模塊用戶using namespace std; // not leaked to module user 不會泄露給模塊用戶export // this is the (only) function seen by users 這是用戶能看見的(唯一)函數template<printable_input_range R> // a range of elements that can be printed using <<//可以使用<< 打印的某范圍中的元素void print(R& s){ cout << "{n"; for (const auto& val: s) cout << " " << val << 'n'; cout << '}';}
10.7.2 Modules – Compile time 模塊—編譯期
Header files (character based)
頭文件(基于字符)
#include<libGalil/DmcDevice.h>int main() { // 457440 lines, 151268 non-blank 457440 行, 151268 非空行 LibGalil::DmcDevice(“192.168.55.10”);} // 1546 milliseconds to compile 編譯時間1546 毫秒Modules (semantic graph) Import libGalil;int main() { // 5 lines, 4 non-blank 5 行, 4 行非空 LibGalil::DmcDevice("192.168.55.10");} // 64 milliseconds to compile 編譯時間64 毫秒
10.7.3 Modules – simplify library use 模塊– 簡化庫的使用
We don’t yet have modules for the standard library
我們還沒有標準庫的模塊
– The 98 standard headers are a source of complexity and confusion – a barrier to entry
– 98 標準的頭文件是復雜性和困惑的來源– 攔路虎
import std;int main(){ std::cout << "Hello modern world!n";}
We can afford that
我們能負擔得起它
The idea generalizes
思想的泛化
– Larger more logical modules
– 更大更有邏輯的模塊
10.8 Concepts 概念
10.8.1 Concepts – constraining template arguments
概念—約束模板實參
C 98 … C 17 checks template arguments at the point of template instantiation
C 98 ... C 17 在模板實例化的時候檢查模板參數
template<class Iter> // Any type: no detailed requirementsvoid sort(Iter first, Iter last) { /* use first and last as iterators使用first 和last 作為迭代器*/ } // the definition is needed for use 定義是需要的sort(vec.begin(),vec.end()); // fine, assuming vec is a vector 可以,假定vec 是vectorsort(7,9); // error: ints are not iterators; the error message is horrible 錯誤:整型不是迭代器;錯誤信息很糟糕
C 20 checks template arguments at the call point
C 20 在調用點檢查模板參數
template<sortable Iter> //how do we define “sortable”? void sort(Iter,Iter); // just a declaration is needed for use 只需要聲明就可以了sort(vec.begin(),vec.end()); // fine, assuming vec is a vector 可以,假定vec 是vectorsort(7,9); // error: ints are not sortable 錯誤:整型不是可排序的
10.8.2 Concepts – use patterns
概念—使用模式
A concept is a compile-time predicate
概念是編譯期謂詞
– A function run at compile time yielding a Boolean
– 編譯期運行并得出一個布爾值的函數
– Takes a set of types and/or values as arguments
– 接受一組類型和/或值作為參數
A concept can be built from fundamental language properties
概念可以從基本語言屬性中創建出來
– Use patterns: show what operations you need
– 使用模式:表明你需要什么操作
– Handles mixed mode arithmetic and implicit conversions
– 處理混合模式算數和隱式轉換
template<typename T, typename U = T>concept equality_comparable = requires(T a, U b) { {a==b} -> Boolean; {a!=b} -> Boolean;;( {b==a} -> Boolean; {b!=a} -> Boolean;}
There are libraries of concepts
<concepts>: equality_comparable
10.8.3 Concepts – composition
概念—組合
A concept is usually constructed from other concepts
概念通常由其他概念構建而成
template<typename R>concept Sortable_range =random_access_range<R>// has begin()/end(), , [], , … 有beign()/end(), ,[], , …&& sortable<iterator_t<R>>;// can compare and swap elements, 能夠比較和交換元素template<typename R>concept Forward_sortable_range =forward_range<R> // has begin()/end(), ; no [] or 有begin()/end(), ; no [] or && sortable<iterator_t<R>>; // can compare and swap elements,能夠比較和交換元素
There are libraries of concepts
<ranges>: random_access_range and sortable
10.8.4 Concepts – Overloading
概念—重載
We can select based on template argument requirements
我們可以基于模板實參要求進行選擇
template<sortable Iter> void sort(Iter,Iter); // a C 98 sort()void sort(Sortable_range auto&); // a C 20 sortvoid sort(Forward_sortable_range auto&); // sort lists, etc. 對列表排序sort(vec.begin(),vec.end()); // OK, as ever 可以,像以往一樣sort(lst.begin(),lst.end());// error, as ever, but with good immediate error message 錯誤,像以往一樣,但是現在有了良好而即時的錯誤信息sort(lst); // sort(Forward_sortable_range auto&)sort(vec) // sort(Sortable_range auto&)
The compiler knows that
編譯器知道
– “Sortable_range is stricter/better than Forward_sortable_range”
– “Sortable_range 比Forward_sortable_range 嚴格/更好”
– We don’t have to explicitly specify that
– 我們無需顯式規約這一點
10.8.5 Concepts – and types
概念—和類型
A type
類型
– Specifies the set of operations that can be applied to an object
– 規約可以在某對象上進行的操作
Implicitly and explicitly
隱式地和顯式地
Relies on function declarations and language rules
依賴于函數聲明和語言規則
– Specifies how an object is laid out in memory
– 規約對象在內存中如何布局
A single-argument concept
單參數概念
– Specifies the set of operations that can be applied to an object
– 規約可以在某對象上進行的操作
Implicitly and explicitly
隱式地和顯式地
Relies on use patterns
依賴于使用模式
– reflecting function declarations and language rules
– 反映函數聲明和語言規則
– Says nothing about the layout of the object
– 不關心對象的布局
– Enables the use of a set of types
– 可以使用集合中的類
10.8.6 Concepts – definition checking
概念—定義檢查
We dreamed of testing template definitions in isolation
我們曾夢想孤立地測試模板定義
void advance(std::input_iterator* p, int n) // input_iterator is a concept input_iterator 是個概念{ p = n; // errorinput_iterator doesn’t require = 錯誤?Input_iterator 不需要 =?}
We figured out how to implement that
我們想出了如何實現這點
We changed our mind
我們改變了主意
– We need stable interfaces
– 我們需要穩定的接口
Change interface every time we change “housekeeping details”(no!)
每次改動“瑣碎細節”的時候都要改變接口?(不行!)
– Debug output
– 調試輸出
– Telemetry
– 遙測
– Data collection
– 數據收集
10.9 Concurrency and parallelism 并發與并行
C : used for concurrency and parallelism from at least 1984
C : 至少從1984 年以來就用于并發和并行
– Coroutines: 1981-1990
– 協程:1981-1990
C 11 – the traditional foundation
C 11 – 傳統的基礎
– Memory model
– 內存模型
– Lock-free programming
– 無鎖編程
– Atomics
– atomic
– Type-safe POSIX/Windows-style treads, mutex, etc.
– 類型安全的POSIX/Windows 風格的線程、互斥鎖等等
– Future and promise
– 期值和promise
C 14, C 17, and C 20
– Many minor improvements (stop tokens, scoped_lock, Fences and barriers, …)
– 許多次要改進(停止令牌、scoped_lock、柵欄和屏障
– Parallel algorithms
– 并行算法
– Coroutines (synchronous and asynchronous)
– 協程(同步和異步)
– Networking (a Technical Specif
10.9.1 Coroutines 協程
Coroutines was the key to C in the early years
協程在早年對于C 很關鍵
– Task library 1981-1990
– 任務庫1981-1990
– Killed by lack of support on SPARC
– 由于缺乏SPARC 上的支持被干掉了
C 20 coroutines: synchronous and asynchronous
C 20 的協程:同步和異步
– Scales to hundreds of thousands of tasks
– 擴展到成百上千個任務上
generator<int> fibonacci() // generate 0,1,1,2,3,5,8,13 … 生成0,1,1,2,3,5,8,13{ int a = 0; int b = 1; // initial state 初始狀態 while(true) { int next = a b; co_yield a; // return next Fibonacci number 返回下一個Fibonacci 數 a = b; b = next; // update state 更新狀態 }}
10.9.2 Parallel algorithms 并行算法
Optional parallel and/or vectorized execution
可選的并行和/或矢量執行
– e.g, sort(par,b,e) and sort(unseq,b,e)
The traditional STL algorithms,
傳統的STL 算法
– e.g., find(seq,b,e,x)
– but no find_all(par,b,e,x) or find_any(par_unseq,b,e,x)
– 但還沒有find_all(par,b,e,x) 或find_any(par_unseq,b,e,x)
parallel algorithms:
并行算法:
– for_each
– reduce // parallel accumulate 并行累加
– exclusive scan
– inclusive scan
– transform reduce
– transform exclusive scan
– transform inclusive scan
– …
11 C 11 example: Range-for, auto, and move
C 11 舉例:范圍for、auto 以及移動
Features must work in combination
特性必須能組合起來使用
template<typename C, typename V>vector<typename C::value_type*>find_all(C& c, V v) // find all occurrences of v in c 找到c 中出現的所有v{ vector<typename C::value_type*> res; for(auto& x : c) if(x==v) res.push_back(&x); return res;}string m {“Mary had a little lamb”}; // simple test code 簡單的測試代碼for(const auto p : find_all(m,‘a’)) // p is a char* p 是個char* if(*p!='a') cerr << "string bug!n";
12 Generic programming
1980: Use macros to express generic types and functions
1980: 使用宏來表達泛型類型和函數
1987 (and current) aims for templates:
1987 年(和現在)模板的目標:
– Extremely general/flexible
– 極為通用/靈活
“must be able to do much more than I can imagine”
"必須能夠做得比我能想象的多得多"
– Zero-overhead
– 零開銷
vector/Matrix/… to compete with C arrays
向量/矩陣/...與C語言數組競爭
– Well-specified interfaces
– 規范的接口
Implying overloading, good error messages, and maybe separate compilation
意味著重載、良好的錯誤信息,以及可能的單獨編譯
2004-2009: C 0x Concepts
2004-2009: C 0x 概念
– Modeled on classes
– 以類為模型
failed: grew complex, costly, incomplete
失?。涸絹碓綇碗s、成本高、不完整
2003-2020: Concepts
2003-2020: 概念
– Compile-time predicates
– 編譯期謂詞
– Precise specification of a template’s requirements on its argument
– 精確說明模板對其參數的要求
13 C in 2020 (the peak so far)
2020 年的C (到目前為止的峰值)
? An invisible foundation of “everything”
? "一切"的無形基礎
– All industries and all countries (and beyond)
– 所有工業和所有國家(并超越這些)
– Better than ever (Shorter, safer, faster code)
– 比以往更好(更短、更安全、更快的代碼)
– More users than ever (at least 5M and increasing)
– 比以往任何時候都多的用戶(至少有500 萬,而且還在增加)
? Huge standards committee participation
? 巨大的標準委員會參與
– Dangers of overenthusiasm and impatience
– 過度熱情和喪失耐心的危險
? Weak in tools
? 工具較弱
– But improving
– 但正在改善
? Often mischaracterized
? 經常被錯誤描述
– People relying on decades old and/or secondary sources
– 人們依賴幾十年前的資料和/或二手資料
? Weak in education
? 在教育方面很薄弱
? Focus on correctness/safety
? 注重正確性/安全性
– Core guidelines
– 核心指南
14 Retrospective
14.1 What could have been done better?
回顧—什么可以做得更好?
? Some key ideas weren’t communicated effectively
? 一些關鍵的想法沒有得到有效的溝通
– Especially to the academic and educational communities
– 特別是對學術和教育界
? Lack of emphasis on tools
? 缺少對工具的強調
– Standard packaging and build system
– 標準的打包和構建系統
– Standard non-textual program representation
– 標準的非文本程序表示法
? Lack of emphasis on use of and distribution of common libraries
? 對通用庫的使用和分發缺乏重視
– Centralized repository for libraries
– 庫的集中倉庫
– General framework for interoperability of libraries
– 庫的互操作性的通用框架
Standard library
標準庫
– Higher-level concurrency support (e.g. a message queue, callbacks for futures)
– 更高級別的并發支持(如消息隊列、期值的回調)
– More libraries support for specific large communities
– 為特定的大型技術社區提供更多的庫支持
Language
語言
– “Smart references”: operator.()
– "智能引用":operator.()
– Unified function call: x.f(y) == f(x,y)
– 統一函數調用:x.f(y) == f(x,y)
– Multi-methods: bool intersect(virtual Shape*, virtual Shape*);
– 多方法:bool intersect(virtual Shape*, virtual Shape*);
14.2 Retrospective – What did C get right?
回顧—C 做對了什么?
Early articulation of principles
早早闡明了原則
Stability and evolution
穩定性和演化
The standards effort
標準化工作
– Difficult, hard work, but it kept the community together
– 困難的、艱苦的工作,但它使社區團結一致
tatic type system
靜態類型系統
– Zero-overhead abstractions
– 零開銷抽象
– Resource management
– 資源管理
Direct access to hardware and system resources
直接訪問硬件和系統資源
Is C 20 better than C 98, C 11, C 14, and C 17?
C 20 比C 98、C 11、C 14 和C 17 好嗎?
– Yes, significantly so
– 是的,顯著地好
– More expressive type system
– 更具表現力的類型系統
– Shorter, safer, faster code
– 更短、更安全、更快的代碼
15 C 23, C 26, … – we have a plan
C 23、C 26、... —我們有個計劃
Top priorities:
最高優先級:
– Library support for coroutines (C 23)
– 庫中對于協程的支持(C 23)
– A modular standard library (C 23)
– 一個模塊化的標準庫(C 23)
– Executors (C 26)
– 執行器(C 26)
– Networking (C 26)
– 網絡(C 26)
Also make progress on
同時在以下方面取得進展
– Multidimensional access (C 23)
– 多維訪問(C 23)
– Flat_map and print (C 23)
– flat_map 和print(C 23)
– Static reflection (C 26)
– 靜態反射(C 26)
– Pattern matching (C 26)
– 模式匹配(C 26)
– Contracts (C 26)
– 契約(C 26)
After that
此外
– Everything else
– 所有其他的
– Many dozens of proposals, many excellent
– 幾十個提案,很多都很棒
ref:
Bjarne_Stroustrup:《現代CPP的發展與演化》at 2022 C Summit
鏈接: https://pan.baidu.com/s/1PU0OG7wuYmOsgcrLcPaEIg?pwd=eh1a 提取碼: eh1a
-End-