С++, группы x36, x37, x38, x39
Лекции
Лекция 1[1]
- i8086
- регистры общего назначения, регистр IP
- операция mov, понятие endian
- распространенные арифметические операции: add, sub, [i]mul, [i]div, inc, dec, neg
- битовые операции, сдвиги: not, and, or, xor, shl, shr, sar
- операция lea
- команды безусловных переходов
- регистр флагов и некоторые биты в нём (ZF, CF, OF, SF)
- команды условных переходов
- команды cmp и test
- i80386, 32-битные регистры
Лекция 2[1]
- (offtopic) деление на константу не используя, команду div[2]
- регистр SP и команды для работы со стеком (push, pop)
- команды call и ret
- регистр BP, стековый фрейм[54][55]
- соглашения вызова функций[9]
Лекция 3[1]
- прерывания
- вытесняющая многозадачность
- защищенный режим, страничная адресация
Лекция 4[3]
- кеш-память[4][5][6]
- translation lookaside buffer
- спекулятивное исполнение команд[25][26]
- branch prediction[27]
- выравнивание
Лекция 5[7]
- пересечение языков C и C++
- целочисленные типы, ABI
- числа с плавающей точкой[8][10]
Лекция 6[7]
- структуры
- указатели
- операции взятия адреса и разыменования
- массивы, неявное приведение к указателю
- операции инкремента, декремента, сложения с числом, вычитание числа и разности указателей
- синтаксис указателей и массивов в общем случае, использование скобок для указания приоритета операций
- указатели на функцию
Лекция 7, 8
- процесс компиляции программ
- объектные файлы
- трансляция, единица трансляция
- линковка[24][45]
- объявления и определения для переменных и для функций
- модификатор static
- препроцессор, примеры директив
- header-файлы
- include guard
- классы, функции члены-класса, неявный аргумент this
- спецификаторы доступа: private, public
- отличие ключевых слов struct, class
- конструкторы, деструкторы
- время жизни объекта
- для объектов c автоматическим storage-class'ом
- для временных объектом
- ссылки, сравнение ссылок с указателями
- перегрузка операторов
- специальные функции члены-класса, правила их генерации
- конструктор по умолчанию
- конструктор копирования
- оператор присваивания
- деструктор
- deleted functions
- выражения new, new[], delete, delete[]
- функции malloc, free
- разница между функциями malloc, free и выражениями new, delete
- наследование, виртуальные функции, таблица виртуальных функции
- как вызвать виртуальную функцию невиртуально?
- спецификатор доступа protected
- абстрактные функции, абстрактные классы
- можно ли вызвать абстрактную функцию?
- виртуальный деструктор
- может ли дектруктор быть абстрактным?
- множественное наследование
- виртуальное наследование, таблица виртуальных баз
- пусть есть два класса B и D. B — виртуальная база D. Можно ли привести B* к D*?
Лекции 13, 14
- исключения[52][53]
- гарантии безопасности исключений[46][47]
- RAII (resource allocation is initialization)
- swap trick
Лекция 15
- механизмы ОС для аллокации памяти
- mmap/munmap
- VirtualAlloc/VirtualFree
- аллокаторы памяти[28]
- small-object optimization[29][30]
- copy-on-write optimization[30]
Лекция 16, 17
- templates
- понятия явной специализации (explicit specialization), частичной специализации (partial specialization) и primary template
- перегрузка функции и специализация функций
- аргументы шаблона по умолчанию
- declaration/expression ambiguities
- порядок инстацирования, неполные типы
- зависимые имена, ключевые слова typename, template
- two-phase name lookup[39]
- Cfront-/borland-способы реализации шаблонов, линковка, ODR
- Явная инстанциация, подавление инстанциации
- type-traits
Лекция 18
Лекция 19
- namespaces, qualified имена
- namespace aliases
- using directive
- using declaration
- anonymous namespaces
- ADL
- C++-style casts
Лекция 20
- strict aliasing rule
- restrict keyword
- undefined behavior[48][49][50]
Лекция 21
- std::shared_ptr
- custom deleter
- shared_ptr на члены-класса
- внутреннее устройство shared_ptr
- std::make_shared
- weak_ptr
- *_pointer_cast
- return value optimization, named return value optimizations
Лекция 22
- rvalue references
- std::auto_ptr
- проблемы auto_ptr, зачем нужен std::unique_ptr
- сравнить
- vector<shared_ptr<file_descriptor>>
- vector<file_descriptor*>
- ptr_vector<file_descriptor>
- vector<unique_ptr<file_descriptor>>
- vector<int>
- vector<file_descriptor>
- rvalue references
- deduction rules
- reference collapsing rule
- std::forward
- noexcept
- variadic templates
Лекция 23
- anonymous functions
- std::function
- понятие type-erasure: std::function, any, any_iterator, any_range
- статический полиморфизм v. динамический полиморфизм
- signals (aka listeners, observers)
Лекция 24
- result_type, протокол result_of
- decltype
- std::optional
- alignment, alignof, alignas
- std::variant
- Boost.TypeErasure
Лекции 25, 26
- понятние многопоточности
- std::thread
- понятие race condition
- std::mutex
- закон Амдала
- понятние deadlock
- std::atomic
- false sharing
- relaxed atomics
- пример concurrent_queue
- std::condition_variable
Домашние задания
- Задание 1
- Задание 2
- Задание 3
- Задание 4
- Задание 5
- Задание 6
Задания для пересдачи
- Bimap
- LRU Cache
- Persistent Set
Литература
Для базового ознакомления с языком Си я бы рекомендовал книгу The C Programming Language[7].
Аналогично совсем базовое ознакомление с C++ можно начать с книги Accelerated C++[11] и книги Бьярна Страуструпа Programming: Principles and Practice using C++[12].
Для более глубокого изучения подходят книги серии C++ In-Depth[13][14][15][16][17][18][19][20][21][22].
Отдельно хотелось бы выделить из этого списка книги Скотта Майерса[17][18], как наиболее популярные и простые для чтения. Лично мне также очень нравиться книга [13].
Я бы не рекомендовал начинать изучение языка с книги[16]. Во-первых, книга достаточно сложна для восприятия. Во-вторых требуется определенный опыт, чтобы увидеть потребность в приемах изложенных в книге. Тем не менее многие вещи изложенные в книге сейчас применяются на практике, правда часто в сильно измененной форме.
Книга [22] достаточно объемная и, возможно, слегка тяжелая для чтения. Но, на мой взгляд, она остается наиболее подробной и содержательной книгой по C++.
Я бы рекомендовал периодически пытаться её открывать и читать, а если не получается возвращаться к более простым книгам.
Ещё один совет, который я могу дать про эту книгу это то, что её не обязательно пытаться читать по порядку от начала до конца. Если какая-то глава, кажется тяжелой, можно её пропустить. Как правило главы относительно независимы и одни главы проще других.
Ссылки
- ^^^ С. В. Зубков — Assembler для DOS, Windows, UNIX
- ^ Henry S. Warren, Jr. — Hacker's Delight
- ^ John P. Shen, Mikko H. Lipasti — Modern Processor Design: Fundamentals of Superscalar Processors
- ^ Ulrich Drepper — What Every Programmer Should Know About Memory
- ^ Tony Albrecht — Pitfalls of Object Oriented Programming
- ^ Paul E. McKenney — Memory Barriers: A Hardware View for Software Hackers
- ^^^ Brian W. Kernighan, Dennis M. Ritchie — The C Programming Language
- ^ David Goldberg — What Every Computer Scientist Should Know About Floating-Point Arithmetic
- ^ Agner Fog — Calling conventions for different C++ compilers and operating systems
- ^ Torbjorn Granlund, Peter L. Montgomery — Division by Invariant Integers using Multiplication
- ^ Andrew Koenig, Barbara Moo — Accelerated C++
- ^ Bjarne Stroustrup — Programming: Principles and Practice using C++
- ^^ Herb Sutter, Andrei Alexandrescu — C++ Coding Standards: 101 Rules, Guidelines, and Best Practices
- ^ Herb Sutter — Exceptional C++
- ^ Herb Sutter — More Exceptional C++
- ^^ Andrei Alexandrescu — Modern C++ Design
- ^^ Scott Mayers — Effective C++
- ^^ Scott Mayers — More Effective C++
- ^^ Scott Mayers — Effective STL
- ^ Stephen Dewhurst — C++ Common Knowledge: Essential Intermediate Programming
- ^ Stephen Dewhurst — C++ Gotchas
- ^^ Bjarne Stroustrup — The C++ Programming Language
- ^ Stanley B. Lippman — Inside the C++ Model
- ^ John R. Levine — Linkers and Loaders
- ^ Yann Collet — Counting bytes fast — little trick from FSE
- ^ POPCOUNT false dependency bug
- ^ A good branch misprediction example
- ^ Emery Berger, Kathryn McKinley, Robert Blumofe, Paul Wilson — Hoard: A Scalable Memory Allocator for Multithreaded Applications
- ^ David Roberts — A look at std::string implementations in C++
- ^^ Nicholas Ormrod — The strange details of std::string at Facebook (CppCon 2016) Slides Video
- Stephan T. Lavavej — STL (C9 Lectures)
- Stephan T. Lavavej — Advanced STL (C9 Lectures)
- Part 1 (Deep shared_ptr and friends)
- ^ Part 2 (Algorithm optimization)
- Part 3 (STL's comprehensive correctness checks)
- Part 4 (rvalue references, perfect forwarding, associative containers)
- Part 5 (Boost Library)
- Part 6 (Container pretty printer)
- Stephan T. Lavavej — Core C++
- Part 1 (Name Lookup)
- Part 2 (Template argument deduction)
- Part 3 (Overload Resolution)
- Part 4 (Virtual Functions)
- Part 5 (Explicit and Partial Specialization)
- Part 6 (C++11 features)
- Part 7 (Usual Arithmetic Conversions, Template Metaprogramming)
- Part 8 (do-while loop, casts, ODR)
- Part 9 (Anonymous functions)
- Part 10 (New features of Visual C++ 2013 CTP)
- Stephan T. Lavavej — STL11: Magic && Secrets Video Slides
- ^ Alexander Stepanov — Notes on Programming
- ^ Alexander Stepanov, Paul McJones — Elements of Programming
- Alexander Stepanov — Наибольшая общая мера последние 2500 лет, лекция в Яндексе
- ^ Alexander Stepanov — Short History of STL
- ^ Doug Gregor — The Dreaded Two-Phase Name Lookup
- ^ Jan Grey — C++: Under the Hood
- Name mangling demystified
- Bjarne Stroustrup — The Design and Evolution of C++
- Bjarne Stroustrup — Evolving a language in and for the real world: C++ 1991-2006
- Rationale for Programming Language C
- ^ Ian Lance Taylor — Linker posts
- Part 1 (Introduction, personal history, first half of what's-a-linker)
- Part 2 (What's-a-linker: Dynamic linking, linker data types, linker operation)
- Part 3 (Address spaces, Object file formats)
- Part 4 (Shared Libraries)
- Part 5 (More Shared Libraries -- specifically, linker implementation; ELF Symbols)
- Part 6 (Relocations, Position Dependent Shared Libraries)
- Part 7 (Thread Local Storage (TLS) optimization)
- Part 8 (ELF Segments and Sections)
- Part 9 (Symbol Versions, Relaxation optimization)
- Part 10 (Parallel linking)
- Part 11 (Archive format)
- Part 12 (Symbol resolution)
- Part 13 (Symbol resolution from the user's point of view; Static Linking vs. Dynamic Linking)
- Part 14 (Link time optimization, aka Whole Program optimization; Initialization Code)
- Part 15 (COMDAT sections)
- Part 16 (C++ Template Instantiation, Exception Frames)
- Part 17 (Warning Symbols)
- Part 18 (Incremental Linking)
- Part 19 (__start and __stop Symbols, Byte Swapping)
- Part 20 (Last post; Update on gold's status)
- ^ Bjarne Stroustrup — Exception Safety: Concepts and Techniques
- ^ Jon Kalb — Exception-Safe Code (CppCon 2014)
Slides
Videos: 1
2
3
- ^ Chris Lattner — What Every C Programmer Should Know About Undefined Behavior
- ^ Chandler Carruth — Garbage In, Garbage Out: Arguing about Undefined Behavior
- ^ Marshall Clow — Undefined Behavior in C++: What is it, and why do you care?
- Kurt Guntheroth — Optimized C++
- ^ Nicolás Brailovsky — C++ exceptions under the hood
- ^ Matt Pietrek — A Crash Course on the Depths of Win32™ Structured Exception Handling (перевод)
- ^ Eli Bendersky — Stack frame layout on x86-64
- ^ Adam Langley — CFI directives in assembly files