чек-лист вопросов, ответы ещё не написаныa question checklist, answers not yet written

Вопросы на собеседованииInterview questions

Плейсхолдеры: только формулировки вопросов, без ответов. 8 категорий от базового ООП до продвинутой памяти и метапрограммирования. Каркас, страницы с разборами ещё не написаны.Placeholders: just the questions, no answers yet. 8 categories from basic OOP to advanced memory and metaprogramming. Skeleton, answer pages not yet written.

1. Основы и ООП1. Basics & OOP

Чем C++ отличается от C? Основные парадигмы языка.How does C++ differ from C? The language's main paradigms. Что такое ООП? Назовите и объясните основные принципы (инкапсуляция, наследование, полиморфизм, абстракция).What is OOP? Name and explain its core principles (encapsulation, inheritance, polymorphism, abstraction). Что такое виртуальная функция? Как работает таблица виртуальных функций (vtable и vptr)?What is a virtual function? How does the virtual function table work (vtable and vptr)? Что такое чисто виртуальная функция и абстрактный класс?What is a pure virtual function and an abstract class? Зачем нужен виртуальный деструктор и что произойдёт, если его не сделать виртуальным при наследовании?Why do you need a virtual destructor, and what happens if it isn't virtual under inheritance? В чём разница между struct и class в C++?What's the difference between struct and class in C++? Что такое перегрузка (overloading) и переопределение (overriding) функций?What is function overloading vs overriding? Что такое спецификаторы доступа public, protected и private?What are the public, protected, and private access specifiers? Что такое виртуальное наследование и какую проблему оно решает (проблема ромба / Diamond Problem)?What is virtual inheritance and what problem does it solve (the diamond problem)? Что делает ключевое слово explicit перед конструктором?What does the explicit keyword do before a constructor? Что такое friend-функции и friend-классы?What are friend functions and friend classes? Чем различаются указатели (pointers) и ссылки (references)?How do pointers differ from references? Что такое ключевое слово inline и как оно влияет на компиляцию?What does the inline keyword do and how does it affect compilation? В чём разница между const, constexpr и consteval?What's the difference between const, constexpr, and consteval? Что означает const после объявления метода класса?What does const after a class method declaration mean? Зачем нужно ключевое слово mutable?What is the mutable keyword for? Что делает static_cast, dynamic_cast, reinterpret_cast и const_cast?What do static_cast, dynamic_cast, reinterpret_cast, and const_cast do? Что такое RTTI (Run-Time Type Information) и какова стоимость его использования?What is RTTI (Run-Time Type Information) and what does it cost to use? Что такое правила трёх, пяти и нуля (Rule of 3 / 5 / 0)?What are the Rule of 3 / 5 / 0? Что делает ключевое слово override и final?What do the override and final keywords do? Что подавляет Rule of 5?What suppresses the Rule of 5? Когда виртуальный вызов не виртуален?When is a virtual call not virtual? Слайсинг: где теряется часть объекта?Slicing: where does part of the object go? Порядок инициализации полейField initialization order i++ в одном выражении дважды — UB?twice in one expression — UB? Перегрузка + неявные преобразованияOverloading + implicit conversions Знаковое переполнение intSigned int overflow

2. Управление памятью и RAII2. Memory management & RAII

Чем отличается стек (stack) от кучи (heap)?How does the stack differ from the heap? Что такое концепция RAII (Resource Acquisition Is Initialization)?What is RAII (Resource Acquisition Is Initialization)? В чём разница между new/delete и malloc/free?What's the difference between new/delete and malloc/free? Что произойдёт, если вызвать delete вместо delete[] для массива?What happens if you call delete instead of delete[] on an array? std::unique_ptr, std::shared_ptr и& std::weak_ptr — как они устроены внутри?— how are they implemented internally? Каковы накладные расходы при использовании std::shared_ptr?What overhead does std::shared_ptr carry? std::weak_ptr — как помогает решить проблему циклических ссылок?— how does it solve the reference-cycle problem? std::make_shared — чем лучше— why is it better than std::shared_ptr<T>(new T())? Что такое утечка памяти (memory leak) и как её обнаружить/предотвратить?What is a memory leak and how do you detect/prevent it? Что такое висячие указатели (dangling pointers) и wild pointers?What are dangling pointers and wild pointers? UB, Implementation-Defined и& Unspecified Behavior — примеры?— examples? Что такое переполнение буфера (buffer overflow)?What is a buffer overflow? Как работает Placement new?How does placement new work? Что такое выравнивание данных (data alignment) и падинг (padding) в структурах?What is data alignment and padding in structs? std::align, alignof / alignas — для чего?what are they for? Что такое сегфолт (Segmentation Fault) и причины его возникновения?What is a segmentation fault and what causes it? Как устроена динамическая память в ОС (страницы, виртуальная память)?How is dynamic memory organized at the OS level (pages, virtual memory)? Что такое custom allocator и в каких случаях его стоит писать?What is a custom allocator and when is it worth writing one? std::addressof — зачем, если есть оператор &?why use it when the & operator exists? Что такое double free и как его избежать?What is a double free and how do you avoid it? const_cast vsvs mutable unique_ptr в API — почему не raw-указатель?in an API — why not a raw pointer?

3. STL: контейнеры, итераторы, алгоритмы3. STL: containers, iterators, algorithms

Основные группы контейнеров в STL (последовательные, ассоциативные, неупорядоченные)?The main STL container groups (sequential, associative, unordered)? std::vector — как устроен внутри? Сложность операций.how is it implemented? Operation complexities. size() vsvs capacity() в vector, работа reserve()/shrink_to_fit()?in vector, how do reserve()/shrink_to_fit() work? Инвалидация итераторов — когда происходит для разных контейнеров?Iterator invalidation — when does it happen for each container? std::vector<bool> — чем отличается от обычного вектора?— how does it differ from a regular vector? std::list и& std::forward_list — как устроены?how are they implemented? std::vector vsvs std::deque — выделение памяти?memory allocation? std::map и& std::set — структура данных, сложность операций?underlying data structure, operation complexity? std::unordered_map и& std::unordered_set — структура данных?underlying data structure? Коллизии в хеш-таблицах — как unordered_map с ними справляется?Hash-table collisions — how does unordered_map handle them? Требования к ключу в std::map (operator<) и std::unordered_map (hash и ==)?Key requirements for std::map (operator<) and std::unordered_map (hash and ==)? emplace_back vsvs push_back Категории итераторов (input, output, forward, bidirectional, random access)?Iterator categories (input, output, forward, bidirectional, random access)? Инвалидация итераторов при удалении из std::map во время цикла?Iterator invalidation when erasing from std::map mid-loop? std::sort — как устроен (Introsort: QuickSort + HeapSort + InsertionSort)?how does it work (Introsort: QuickSort + HeapSort + InsertionSort)? std::find, std::binary_search, std::lower_bound, std::upper_bound — разница?what's the difference? std::string_view и& std::span — зачем нужны?what are they for? std::flat_map и& std::flat_set (C++23) Инвалидация ссылки vs инвалидация итератора — разница?Reference invalidation vs iterator invalidation — what's the difference? Префиксный (++i) vs постфиксный (i++) инкремент итераторов?Prefix (++i) vs postfix (i++) increment for iterators? std::vector — почему push_back амортизированно O(1)?why is push_back amortized O(1)? std::map vsvs std::unordered_map Small String Optimization — что это?what is it?

4. Шаблоны и метапрограммирование4. Templates & metaprogramming

Что такое шаблоны функций и классов? Как происходит инстанцирование?What are function and class templates? How does instantiation work? Явная и частичная специализация шаблонов?Explicit vs partial template specialization? SFINAE (Substitution Failure Is Not An Error) — что это?what is it? std::enable_if — зачем нужен и как работает?why is it needed and how does it work? Concepts и Constraints (C++20) — чем лучше SFINAE?and Constraints (C++20) — how are they better than SFINAE? Variadic Templates — шаблоны с переменным числом аргументов?templates with a variable number of arguments? Fold Expressions (C++17) — раскрытие сверток?fold expression expansion? typename в контексте зависимых имён (dependent names)?in the context of dependent names? <type_traits> — для чего используется?what is it used for? Метапрограммирование на шаблонах — вычисления на этапе компиляции?Template metaprogramming — compile-time computation? template перед вызовом метода зависимого типа — зачем?before a dependent-type method call — why? Tag Dispatching — что это?what is it? constexpr функции vs шаблоны — разница?functions vs templates — what's the difference? std::conditional и& std::decay Почему реализацию шаблонов чаще выносят в .h, а не в .cpp?Why is template implementation usually put in .h rather than .cpp? Two-Phase Name Lookup при компиляции шаблонов?during template compilation? Explicit Instantiation vs Explicit Specialization?vs Explicit Specialization? Почему partial specialization разрешена для классов, но не для функций? Как обойти?Why is partial specialization allowed for classes but not functions? How do you work around it? ADL (Argument-Dependent Lookup) — взаимодействие с шаблонами?how does it interact with templates? CRTP (Curiously Recurring Template Pattern) — кейсы применения?use cases? Deduction guides (C++17) — как писать для своих классов?how do you write them for your own classes? Template Argument Deduction для L-value и R-value ссылок?for L-value and R-value references? Reference Collapsing — таблица сворачивания?the collapsing table? decltype(expr) vsvs decltype((expr)) decltype(auto) — разница с auto?how does it differ from auto? Как написать свой тип-трейт (аналог is_same/is_base_of)?How do you write your own type trait (an is_same/is_base_of analog)? std::void_t — SFINAE-проверка наличия метода/поля?an SFINAE check for a method/field's presence? requires-expression vs requires-clause (C++20)?vs requires-clause (C++20)? Subsumption rules — выбор наиболее специализированной перегрузки через Concepts?choosing the most specialized overload via Concepts? Abbreviated Function Templates (C++20) — auto в аргументах обычной функции?as a regular function parameter type? Parameter Packs (Args...) — раскрытие через рекурсию vs Fold Expressions?expansion via recursion vs fold expressions? Factorial<N>/Fibonacci<N> во время компиляции — шаблоны vs constexpr?at compile time — templates vs constexpr? std::tuple — как устроен? Извлечение по индексу через std::get<I>?how is it implemented? Index-based extraction via std::get<I>? Expression Templates — оптимизация математических библиотек (Eigen, Blitz++)?optimizing math libraries (Eigen, Blitz++)? Typelist — реализация операций (Push, Pop, Find)?implementing operations (Push, Pop, Find)? std::integral_constant vs обычные enum/static const в метапрограммировании?vs plain enum/static const in metaprogramming? std::apply и& std::make_from_tuple

5. Move-семантика и современный C++5. Move semantics & modern C++

6. Многопоточность и низкоуровневые темы6. Concurrency & low-level topics

Разница между процессом и потоком (thread)?Process vs thread — what's the difference? Что такое состояние гонки (Data Race / Race Condition)?What is a data race / race condition? std::mutex, std::recursive_mutex, std::shared_mutex — разница?what's the difference? std::lock_guard, std::unique_lock, std::scoped_lock — чем отличаются?how do they differ? std::condition_variable — как предотвратить ложные пробуждения (spurious wakeups)?how do you prevent spurious wakeups? std::atomic и атомарные операции?and atomic operations? Модель памяти C++ и порядки памяти (relaxed, acquire-release, seq_cst)?The C++ memory model and memory orders (relaxed, acquire-release, seq_cst)? std::future, std::promise и& std::async std::jthread (C++20) — чем отличается от std::thread?how does it differ from std::thread? False Sharing — как бороться через std::hardware_destructive_interference_size?— how do you fight it with std::hardware_destructive_interference_size? Lock-free программирование и ABA-проблема?programming and the ABA problem? thread_local переменные?variables? std::memory_order — разница между relaxed и acquire/release?relaxed vs acquire/release? Почему shared_ptr не защищает от гонок?Why doesn't shared_ptr prevent races? Deadlock на двух мьютексах — как воспроизвести и починить?on two mutexes — how to reproduce and fix?

7. Глубокая память7. Deep memory

ОС, аллокаторы, редкие нюансыthe OS, allocators, rare edge cases
Менеджер памяти ОС (Virtual Memory, Page Tables, TLB, Page Fault)?The OS memory manager (virtual memory, page tables, TLB, page faults)? Minor, Major и& Invalid Page Faults — чем отличаются?how do they differ? Cache Miss (L1/L2/L3) — как Data Locality влияет на перформанс?how does data locality affect performance? SIMD, alignas — почему misaligned access может снижать скорость или вызывать UB?why can misaligned access hurt speed or cause UB? sbrk и& mmap в Linux — как malloc (glibc ptmalloc) выбирает между ними?in Linux — how does malloc (glibc ptmalloc) choose between them? Фрагментация памяти (внутренняя и внешняя) — какие алгоритмы её минимизируют (buddy, slab, arena)?Memory fragmentation (internal and external) — which allocators minimize it (buddy, slab, arena)? Stack overflow на уровне ОС (Guard Pages) — как предотвратить исчерпание стека?at the OS level (guard pages) — how do you prevent stack exhaustion? alloca / VLA — почему это опасная практика?why is this dangerous practice? Control Block в std::shared_ptr — что там хранится помимо счётчиков?in std::shared_ptr — what does it store besides the counters? Почему кастомный deleter меняет тип unique_ptr<T, Deleter>, но не меняет тип shared_ptr<T>?Why does a custom deleter change unique_ptr<T, Deleter>'s type but not shared_ptr<T>'s? Что происходит с памятью, если конструктор объекта бросает исключение внутри new?What happens to memory if a constructor throws inside new? Безопасен ли shared_ptr при работе из разных потоков? Что атомарно, а что нет?Is shared_ptr thread-safe? What's atomic and what isn't? std::atomic_ref vsvs std::atomic<std::shared_ptr> std::enable_shared_from_this — какая ошибка при вызове в конструкторе?what's the classic mistake when calling it from the constructor? Как написать минимальный кастомный аллокатор (std::allocator_traits)?How do you write a minimal custom allocator (std::allocator_traits)? Polymorphic Memory Resources (PMR, C++17) — какую проблему решают?what problem do they solve? Small Buffer Optimization (SBO) в string/function — как проверить размер буфера?in string/function — how do you check the buffer size? Виртуальная память при множественном/виртуальном наследовании (this adjustment)?Virtual memory under multiple/virtual inheritance (this-pointer adjustment)? Copy-on-Write (COW) для строк — почему отказались в C++11?for strings — why was it dropped in C++11? std::launder — какую проблему strict aliasing решает?what strict-aliasing problem does it solve? Strict Aliasing Rule — как reinterpret_cast/char* его нарушают?how do reinterpret_cast/char* violate it? std::construct_at и& std::destroy_at (C++20) delete this — когда это легитимно?when is it legitimate? Value, Direct, Zero и& Default Initialization — разница?what's the difference? std::scoped_allocator_adaptor — зачем во вложенных контейнерах?why is it needed in nested containers? new T vsvs new T() — разница?what's the difference? OOM (Linux OOM Killer) — как перехватить bad_alloc или задать set_new_handler?(Linux OOM Killer) — how do you catch bad_alloc or set a set_new_handler? Non-owning vs owning указатели — дизайн через observer_ptr/raw pointers?vs owning pointers — designing with observer_ptr/raw pointers? Garbage collection / hazard pointers / epoch-based reclamation в lock-free структурах?in lock-free data structures? std::uninitialized_fill и& std::uninitialized_move — где применяются в STL?where are they used inside STL?

8. Глубокие шаблоны8. Deep templates

compile-time генерация, новинки стандартаcompile-time generation, newer standard features

статусstatus

Это чек-лист, а не каркас со страницами: 8 категорий, только формулировки вопросов, ответов и разборов пока нет ни у одного вопроса. Общие алгоритмические вопросы (сложность, паттерны) сюда не входят — они уже покрыты в cpp/algorithms/, здесь — то, что специфично именно для C++.This is a checklist, not a skeleton with pages: 8 categories, question wording only — no answers or explanations exist yet for any of them. General algorithmic questions (complexity, patterns) aren't included here — those already live in cpp/algorithms/; this section covers what's specific to C++.