📚 Modern C++ Tutorial: C++11/14/17/20 On the Fly

logo

Modern C++ Tutorial: C++11/14/17/20 On the Fly

Purpose

The book claims to be "On the Fly". Its intent is to provide a comprehensive introduction to the relevant features regarding modern C++ (before 2020s). Readers can choose interesting content according to the following table of content to learn and quickly familiarize the new features you would like to learn. Readers should be aware that not all of these features are required. Instead, it should be learned when you really need it.

At the same time, instead of coding-only, the book introduces the historical background of its technical requirements (as simple as possible), which provides great help in understanding why these features came out.

In addition, the author would like to encourage readers to use modern C++ directly in their new projects and migrate their old projects to modern C++ gradually after reading the book.

Targets

  • This book assumes that readers are already familiar with traditional C++ (i.e. C++98 or earlier), or at least that they do not have any difficulty in reading traditional C++ code. In other words, those who have long experience in traditional C++ and people who desire to quickly understand the features of modern C++ in a short period of time are well suited to read the book.

  • This book introduces, to a certain extent, the dark magic of modern C++. However, these magic tricks are very limited, they are not suitable for readers who want to learn advanced C++. The purpose of this book is offering a quick start for modern C++. Of course, advanced readers can also use this book to review and examine themselves on modern C++.

Start

You can choose from the following reading methods:

Code

Each chapter of this book contains a lot of code. If you encounter problems while writing your own code with the introductory features of the book, reading the source code attached to the book might be of help. You can find the book here. All the code is organized by chapter, the folder name is the chapter number.

Exercises

There are few exercises at the end of each chapter of the book. These are ment to test whether you have mastered the knowledge in the current chapter. You can find the possible answer to the problem here. Again, the folder name is the chapter number.

Website

The source code of the website of this book can be found here, which is built by hexo and vuejs. The website provides you another way of reading the book, it also adapts to mobile browsers.

Build

If you are interested in building everything locally, it is recommended using Docker. To build, simply run:

$ make build

Acknowledgements

This book was originally written in Chinese by Changkun Ou.

The author has limited time and language skills. If readers find any mistakes in the book or any language improvements, please feel free to open an Issue or start a Pull request. For detailed guidelines and checklist, please refer to How to contribute.

The author is grateful to all contributors, including but not limited to Contributors.

This project is also supported by:

Licenses

Creative Commons License
This work was written by Ou Changkun and licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. The code of this repository is open sourced under the MIT license.

Owner
Comments
  • 有关 void * 的表述

    有关 void * 的表述

    在某种意义上来说,传统 C++ 会把 NULL、0 视为同一种东西,这取决于编译器如何定义 NULL,有些编译器会将 NULL 定义为 ((void*)0),有些则会直接将其定义为 0。

    且不论“编译器”定义 NULL 的说法来源是什么,“传统 C++”是指 ISO C++ 之前的(如由 Annotated Reference Manual 定义的) C++ 还是 ISO C++11 以前的 C++ ?指代不明。

    注意 http://eel.is/c++draft/support.types.nullptr#footnote-187 是在什么时候引入的,烦请重新校对内容质量。

    隐式转换到其他类型(换句话说,void * 并不属于 C++ 语言的一部分)

    依据?

  • 关于线程方面的疑问

    关于线程方面的疑问

    https://github.com/changkun/modern-cpp-tutorial/blob/master/book/zh-cn/07-thread.md 里面7.4的代码,

     while (!notified) { // 循环避免虚假唤醒
        cond_var.wait(lock);
    }
    

    notefied变量非volatile,是否存在这种问题:编译器优化时将其放置在寄存器中,线程更改变量时没有更新寄存器的变量,导致卡死

  • Fix bug#102, typor#103

    Fix bug#102, typor#103

    resolve #102 resolve #103

    Description

    fixed bug#102

    Change List

    • Fix bug#102 of string literal is a rvalue just in class context

    • Resolve error content of book/en-US/03-runtime.md


    说明

    解决 bug#102, typor#103

    变化箱单

    • 修复了关于字符串仅在类中为右值的说明
  • 在没有自定义初始化列表构造函数的类中,可以用初始化列表直接初始化对象吗?

    在没有自定义初始化列表构造函数的类中,可以用初始化列表直接初始化对象吗?

    实际描述

    • 文件路径:book/zh-cn/02-usability.md
    • 原文段落:

    而对于类对象的初始化,要么需要通过拷贝构造、要么就需要使用 () 进行。 这些不同方法都针对各自对象,不能通用。

    但是又写道:

    其次,C++11 还提供了统一的语法来初始化任意的对象,例如:

    Foo foo2 {3, 4};
    
  • website: improve readability

    website: improve readability

    Motivation

    Please briefly describe your motivation.

    Requirements

    Please list all of your suggestions.


    动机

    我访问了在线版 https://changkun.de/modern-cpp/ 的中文版,发现代码字体非常细,读起来很吃力,换成 PDF 版本才好了些(但对我来说还是不够粗)。

    需求说明

    希望提供一个模式,可以更换代码排版使用的字体到笔画更粗的字体,或者让用户自己填?如果同时能更换正文字体那就更好了。

    单纯的横向加粗应该不够,比如一横加粗完还是一横,仍然不够显眼。我希望的用是黑体、雅黑这种无论横竖笔画都很粗的字体。

    谢谢!

  • ## 第二章 2.3类型推导中的一个疑问

    ## 第二章 2.3类型推导中的一个疑问

    Motivation

    Please briefly describe your motivation.

    Requirements

    Please list all of your suggestions.


    动机

    请描述你提交内容建议的动机。

    需求说明

    请描述你提交内容建议的详单,例如具体是增加哪个知识点的说明。

  • example of

    example of "default template parameters", chapter02 could be misleading

    原文第二章关于默认模板参数的优点的示例代码: // c++11 version template<typename T, typename U> auto add(T x, U y) -> decltype(x+y) { return x+y; } // Call add function auto ret = add<int, int>(1,3);

    该示例代码并不能体现出默认模板参数的作用,因为示例代码即使不指定出参数类型,也可以通过模板参数自动推倒得到。原文的 “要使用 add,就必须每次都指定其模板参数的类型” 这句话可能引发误导。

  • 一些疑问🤔️

    一些疑问🤔️

    在网上看到一些跟书中大量重复,相似的内容,不知道到底哪个是原创?

    例如: 关于第2章语言可用性的强化: 这篇csdn博客跟作者的内容大量重复,但是这篇博客2016年就存在了,并标明根据实验楼的课程整理而来。 看了实验楼这门课的作者,叫欧龙崎,不知道跟作者是什么关系?

    image

    image

    image

    以下为疑似原创链接:

    • csdn课程笔记:https://blog.csdn.net/taoyanqi8932/article/details/53186055
    • 实验楼课程:https://www.lanqiao.cn/courses/605
    • 知乎链接:https://zhuanlan.zhihu.com/p/22283367

    另外,作者采用MIT开源协议,如果大量引用,摘抄别问的原创知识是否应该注明出处?或者获取原创作者的许可及授权?

  • 范型lambda表达式 -> 后少返回自动类型推断关键字auto

    范型lambda表达式 -> 后少返回自动类型推断关键字auto

    Actual Description

    • File Path: for example, book/en-us/02-usability.md
    • Original paragraph:
    A copy of the original paragraph
    

    Expected Description

    A modified paragraph
    

    Attachments

    Attach screenshot or files if necessary.


    实际描述

    • 文件路径:例如,book/zh-cn/02-usability.md
    • 原文段落:
    复制原文段落
    

    预期描述

    修改后的段落
    

    附图

    必要时,请附上相关截图

  • Create bits

    Create bits

    resolve #issue_id

    Description

    Please describe the motivation of this pull request, and what problem was solved in this PR.

    Change List

    • Fix typo error of XXX
    • Add description regarding XXX feature
    • Resolve error content of XXX

    Reference

    Please add reference if necessary


    说明

    此处详细说明 PR 的动机是什么、解决了什么样的问题。

    变化箱单

    • 修复了 XXX 的 typo 错误
    • 增加了 XXX 相关的说明
    • 解决了关于 XXX 的描述性错误

    参考文献

    如果有请注明

  • 9.2 noexcept部分代码或许存在问题

    9.2 noexcept部分代码或许存在问题

    9.2 noexcept 修饰完一个函数之后能够起到封锁异常扩散的功效,如果内部产生异常,外部也不会触发。

    我的理解是不会触发异常而执行catch中的代码, 如果我的理解正确的话:

    之后给出的代码好像并不能体现出这一特性,

    没有noexcept修饰符的my_throw()抛出了异常,但执行了catch中的代码 2,没有noexcept修饰符的non_block_throw()抛出了异常,也执行了catch中的代码 3,具有noexcept修饰符的block_throw()函数并没有抛出异常,当然也没有触发catch中的代码 4,于是我自做主张为my_throw() 增加了noexcept操作符使其声明变为 void may_throw() noexcept 这样的情况下: 4-1,编译器会发出警告( warning C4297: “may_throw”: 假定函数不引发异常,但确实发生了) 以及(note: 在函数上指定了 __declspec(nothrow)、throw()、noexcept(true)或 noexcept)(vs2017) 4-2,运行期间,程序直接异常退出。与我理解相反地,这个异常不能被try...catch语句捕捉,或许这才 你所要表达的“如果内部产生异常,外部也不会触发(try...catch语句)。”?

  • Ranges

    Ranges

    尽管我看到 https://github.com/changkun/modern-cpp-tutorial/issues/1 中的 Ranges 打对号了,但是似乎实际上并没有内容。

    实在是抱歉,这一段时间因为需要准备秋招,所以我可能没时间弄 PR 了。今天看到这个项目想起来我 Range 做的笔记了,这里贴出来希望能对你有所帮助:

    Ranges 本身内容比较少,所以确实也没什么可写的,主要特征应该是 数据不变 和管道符的使用吧。我本身的笔记是 rst 的,转成 md 后多出来了一部分换行

    这里是预览:

    Range

    Range 是 C++ 社区对 反应式编程 () 的回应。最初由 boost 社区实现, v3 版本 分离出来成为 C++ 20 标准库的基础。与其类似的还有 RxCpp 。Range 相当于 RxCpp 的数据处理部分。

    反应式编程是基于 数据流 (Data Stream)变化传递 (Propagation of Change Value)声明式 编程方式。数据在传递过程中保持不变。原始数据通过通道符传递到一个一个 view 中,view 对数据进行处理之后又形成了新的数据,就这样,数据通过管道符在一个一个 view 中流动中发生变化,最终成品。

    先看一个简单的 Demo 以对 Range 有初步的印象:

    #include <iostream>
    #include <ranges>
    #include <vector>
    
    using namespace std;
    
    int main() {
       vector<int> ints { 0, 1, 3, 4, 5 };
       auto res = ints | views::filter([](int item) {
          return item % 2;
       }) | views::transform([](int item) {
          return item * item;
       });
       for(auto const& item : res){
          cout << item << ", ";
       }
       return 0;
    }
    

    如代码所述,原始的数据 ints 在成品(形成 res)的过程中分别经过过滤(views::filter)、转换(views::transform)形成,最后由 for 将成品打印出来。ints 在这过程中始终保持不变。

    概述

    Range 库由头文件 <ranges> 提供,并带来一个命名空间 std::views 。 std::views 名为 视图适配器 ,负责对数据的处理,常用的视图适配器如下:

    | | | | | ----------------------------------------------------------------------------- | ------- | --------------------- | | view::filter | 谓词 | 根据谓词过滤数据 | | view::transform | 函数 | 将数据进行变形 | | view::take | size_t | 取走前几个数据 | | view::drop | size_t | 丢弃前几个数据 | | view::join | 数据流 | 将上一个数据流与指定数据流合并 | | view::split | str | 将上一个数据流根据 str 分割为多个数据 | | view::keys | 数据流 | 从 map 数据流中提取 key | | view::values | 数据流 | 从 map 数据流中提取 value | | view::reverse | none | 反转数据流中数据的顺序 | | view::take_while | 谓词 | 过滤满足谓词条件的数据 | | view::iota | <i,i> | 产生范围数据 | | view::single | data | 产生单个数据 |

    这里是源码: Range.md

  • proposal: discuss internals regarding for loop

    proposal: discuss internals regarding for loop

    Motivation

    Please briefly describe your motivation.

    Requirements

    Please list all of your suggestions.


    动机

    区间for循环可以加上内部机制;读者可以更加灵活运用区间for循环

    需求说明

    比如for循环作用于自己定义的容器模板;该容器需要包含begin和end模板成员函数; for(auto x : range_expression)内部机制: { init-statement auto && __range = range_expression ; auto __begin = begin_expr ; auto __end = end_expr ; for ( ; __begin != __end; ++__begin) { range_declaration = *__begin; loop_statement } } 引用:https://en.cppreference.com/w/cpp/language/range-for

  • Add C++20 Supports

    Add C++20 Supports

    需要支持以下内容:

    • 语言级 bug 与修订
    • [ ] 类型系统改进 Type Punning
    • [x] 弃用和删除的功能
      • register
      • std::auto_ptr --> std::unique_ptr
      • std::random_shuffle
      • std::bind1st, std::bind2nd, ...
    • 语言增强
    • [x] 结构化绑定 Structured bindings
    • [x] 新的控制结构 constexpr if
    • [x] 编译时条件语句 Compile-time conditional statements
    • [ ] 新的聚合规则
    • [ ] 强制性 RVO 和复制 elision, Guaranteed copy elision
    • [ ] Unary static_assert
    • [ ] 嵌套命名空间 Nested namespace deinitions
    • [ ] inline 变量 inline variables
    • [ ] constexpr 改进, constexpr lambda
    • 模板增强
    • [x] 折叠表达式 Fold expressions
    • [x] 类模板参数推导 Class template deduction
    • [x] variadic templates fold
    • [x] auto non-type template parameters
    • [ ] ~~Preprocessor predicate for header testing~~
    • 容器
    • [ ] std::string_view, std::byte 加入 container 容器一章
    • [x] std::any, std::variant, std::optional 加入 container 容器一章
    • [ ] 容器改进
    • 线程
    • 文件系统
    • [x] [文件系统库, 专门用一章来讲解](http://en.cppreference.com/w/cpp/filesystem, http://www.bfilipek.com/2017/08/cpp17-details-filesystem.html)
    • 数学库
    • 其他特性
    • [ ] Polymorphic allocators and memory resources
    • [ ] Aligned new
    • [ ] Improved insertion and splicing for associative constrainers
    • [ ] Boolean logic metafunctions ...
    • 展望 C++20
    • [x] concept
    • [x] module
    • [x] coroutine
    • [x] Ranges
This is a code repository for pytorch c++ (or libtorch) tutorial.

LibtorchTutorials English version 环境 win10 visual sutdio 2017 或者Qt4.11.0 Libtorch 1.7 Opencv4.5 配置 libtorch+Visual Studio和libtorch+QT分别记录libtorch在VS和Q

Sep 20, 2022
In this tutorial, we will use machine learning to build a gesture recognition system that runs on a tiny microcontroller, the RP2040.
In this tutorial, we will use machine learning to build a gesture recognition system that runs on a tiny microcontroller, the RP2040.

Pico-Motion-Recognition This Repository has the code used on the 2 parts tutorial TinyML - Motion Recognition Using Raspberry Pi Pico The first part i

Sep 7, 2022
tutorial on how to train deep learning models with c++ and dlib.

Dlib Deep Learning tutorial on how to train deep learning models with c++ and dlib. usage git clone https://github.com/davisking/dlib.git mkdir build

Dec 21, 2021
C-based/Cached/Core Computer Vision Library, A Modern Computer Vision Library

Build Status Travis CI VM: Linux x64: Raspberry Pi 3: Jetson TX2: Backstory I set to build ccv with a minimalism inspiration. That was back in 2010, o

Sep 21, 2022
A modern object detector inside fragment shaders
A modern object detector inside fragment shaders

YOLOv4 Tiny in UnityCG/HLSL Video Demo: https://twitter.com/SCRNinVR/status/1380238589238206465?s=20 Overview YOLOv4 Tiny is one of the fastest object

Sep 15, 2022
A Modern C++ Data Sciences Toolkit

MeTA: ModErn Text Analysis Please visit our web page for information and tutorials about MeTA! Build Status (by branch) master: develop: Outline Intro

Sep 19, 2022
A fast and modern voxel based raytracing engine

CubiCAD A fast and modern voxel based raytracing engine Currently in heavy development and unusable at its current state. This reposity will hold the

Sep 6, 2022
A collection of as simple as possible, modern CMake projects

Modern CMake Examples Overview This repository is a collection of as simple as possible CMake projects (with a focus on installing). The idea is to tr

Sep 15, 2022
Modern(-ish) password hashing for your software and your servers

bcrypt Good password hashing for your software and your servers Installation To install bcrypt, simply: $ pip install bcrypt Note that bcrypt should b

Sep 16, 2022
📚 Modern C++ Tutorial: C++11/14/17/20 On the Fly
📚 Modern C++ Tutorial: C++11/14/17/20 On the Fly

The book claims to be "On the Fly". Its intent is to provide a comprehensive introduction to the relevant features regarding modern C++ (before 2020s). Readers can choose interesting content according to the following table of content to learn and quickly familiarize the new features you would like to learn. Readers should be aware that not all of these features are required. Instead, it should be learned when you really need it.

Sep 21, 2022
✔️The smallest header-only GUI library(4 KLOC) for all platforms
✔️The smallest header-only GUI library(4 KLOC) for all platforms

Welcome to GUI-lite The smallest header-only GUI library (4 KLOC) for all platforms. 中文 Lightweight ✂️ Small: 4,000+ lines of C++ code, zero dependenc

Sep 21, 2022
multi-sdr-gps-sim generates a IQ data stream on-the-fly to simulate a GPS L1 baseband signal using a SDR platform like HackRF or ADLAM-Pluto.

multi-sdr-gps-sim generates a GPS L1 baseband signal IQ data stream, which is then transmitted by a software-defined radio (SDR) platform. Supported at the moment are HackRF, ADLAM-Pluto and binary IQ file output. The software interacts with the user through a curses based text user interface (TUI) in terminal.

Sep 19, 2022
This project aims to facilitate debugging a kernel driver in windows by adding support for a code change on the fly without reboot/unload, and more!
This project aims to facilitate debugging a kernel driver in windows by adding support for a code change on the fly without reboot/unload, and more!

BSOD Survivor Tired of always telling yourself when you got a BSOD that what if I could just return to the caller function which caused the BSOD, and

Aug 23, 2022
C++ Live Toolkit are tools subset used to perform on-the-fly compilation and running of cpp code

C++ Live Toolkit CLT (C++ Live Toolkit) is subset of tools that are very light in size, and maintained to help programmers in compiling and executing

Jan 4, 2022
A kernel module that patches Linux kernel "on-the-fly" to skip TASK_RSS_EVENTS_THRESH check in check_sync_rss_stat

split-rss-counting-patch A kernel module that patches Linux kernel "on-the-fly" to skip TASK_RSS_EVENTS_THRESH check in check_sync_rss_stat. Why? Read

Mar 6, 2022
Tutorial/Example to deal with modern cmake.

modern_cmake Tutorial/Example to deal with modern cmake. This tutorial assume that you already know how to write a CMakeLists.txt Introduction This re

Sep 9, 2022
A gtk4 tutorial for beginners

This tutorial illustrates how to write C programs with Gtk4 library. It focuses on beginners so the contents are limited to basic things such as widgets, GObject, signal, menus and build system. Please refer Gnome API reference for further topics.

Sep 21, 2022
This is a code repository for pytorch c++ (or libtorch) tutorial.

LibtorchTutorials English version 环境 win10 visual sutdio 2017 或者Qt4.11.0 Libtorch 1.7 Opencv4.5 配置 libtorch+Visual Studio和libtorch+QT分别记录libtorch在VS和Q

Sep 20, 2022
Nvidia contributed CUDA tutorial for Numba

This is an adapted version of one delivered internally at NVIDIA - its primary audience is those who are familiar with CUDA C/C++ programming, but perhaps less so with Python and its ecosystem.

Sep 5, 2022
In this tutorial, we will use machine learning to build a gesture recognition system that runs on a tiny microcontroller, the RP2040.
In this tutorial, we will use machine learning to build a gesture recognition system that runs on a tiny microcontroller, the RP2040.

Pico-Motion-Recognition This Repository has the code used on the 2 parts tutorial TinyML - Motion Recognition Using Raspberry Pi Pico The first part i

Sep 7, 2022