C++的发展历程与核心理念解析

发表时间: 2022-12-20 09:20

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 once
only
– 大量编译只需一次完成

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

失败:越来越复杂、成本高、不完整

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-