C++ Expert
Expert guidance for modern C++ development including C++20/23 features, STL, templates, memory management, and high-performance programming.
Core Concepts
Modern C++ Features (C++20/23)
- Concepts and constraints
- Ranges and views
- Coroutines
- Modules
- Three-way comparison (spaceship operator)
- std::format
- std::span
- Designated initializers
- consteval and constinit
Memory Management
- RAII (Resource Acquisition Is Initialization)
- Smart pointers (unique_ptr, shared_ptr, weak_ptr)
- Move semantics and perfect forwarding
- Memory allocation strategies
- Custom allocators
- Memory pools
Performance
- Zero-cost abstractions
- Inline optimization
- Template metaprogramming
- Compile-time computation (constexpr)
- Cache-friendly data structures
- SIMD operations
STL Containers
Sequential Containers
#include <vector>
#include <deque>
#include <list>
#include <array>
// vector - dynamic array
std::vector<int> vec = {1, 2, 3, 4, 5};
vec.push_back(6);
vec.emplace_back(7); // Construct in-place
vec.reserve(100); // Pre-allocate capacity
// deque - double-ended queue
std::deque<int> deq = {1, 2, 3};
deq.push_front(0);
deq.push_back(4);
// list - doubly-linked list
std::list<int> lst = {1, 2, 3};
lst.push_front(0);
lst.push_back(4);
lst.remove(2); // Remove all elements with value 2
// array - fixed-size array
std::array<int, 5> arr = {1, 2, 3, 4, 5};
Associative Containers
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
// map - ordered key-value pairs
std::map<std::string, int> ages;
ages["Alice"] = 30;
ages["Bob"] = 25;
ages.insert({"Charlie", 35});
// set - ordered unique elements
std::set<int> numbers = {3, 1, 4, 1, 5, 9};
numbers.insert(2);
// unordered_map - hash table
std::unordered_map<std::string, int> hash_map;
hash_map["key"] = 42;
// unordered_set - hash set
std::unordered_set<int> hash_set = {1, 2, 3};
Algorithms
#include <algorithm>
#include <numeric>
#include <vector>
std::vector<int> numbers = {5, 2, 8, 1, 9, 3, 7};
// Sorting
std::sort(numbers.begin(), numbers.end());
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
// Searching
auto it = std::find(numbers.begin(), numbers.end(), 8);
bool found = std::binary_search(numbers.begin(), numbers.end(), 5);
// Transforming
std::vector<int> doubled(numbers.size());
std::transform(numbers.begin(), numbers.end(), doubled.begin(),
[](int n) { return n * 2; });
// Filtering
std::vector<int> evens;
std::copy_if(numbers.begin(), numbers.end(), std::back_inserter(evens),
[](int n) { return n % 2 == 0; });
// Accumulate
int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
int product = std::accumulate(numbers.begin(), numbers.end(), 1,
std::multiplies<int>());
// Partition
auto pivot = std::partition(numbers.begin(), numbers.end(),
[](int n) { return n < 5; });
// Remove
numbers.erase(std::remove(numbers.begin(), numbers.end(), 5), numbers.end());
// Unique (remove consecutive duplicates)
std::sort(numbers.begin(), numbers.end());
numbers.erase(std::unique(numbers.begin(), numbers.end()), numbers.end());
Concurrency
#include <thread>
#include <mutex>
#include <future>
#include <atomic>
// Thread
void worker(int id) {
std::cout << "Thread " << id << '\n';
}
std::thread t1(worker, 1);
std::thread t2(worker, 2);
t1.join();
t2.join();
// Mutex
std::mutex mtx;
int shared_data = 0;
void increment() {
std::lock_guard<std::mutex> lock(mtx);
++shared_data;
}
// Atomic
std::atomic<int> counter{0};
counter++; // Thread-safe
counter.fetch_add(5);
// Future and promise
std::promise<int> prom;
std::future<int> fut = prom.get_future();
std::thread t([&prom]() {
std::this_thread::sleep_for(std::chrono::seconds(1));
prom.set_value(42);
});
int result = fut.get(); // Blocks until ready
t.join();
// async
auto future = std::async(std::launch::async, []() {
return 42;
});
int value = future.get();
Build Systems
CMake
# CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(MyApp VERSION 1.0.0 LANGUAGES CXX)
# Set C++ standard
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Compiler flags
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
add_compile_options(-Wall -Wextra -Wpedantic -O3)
endif()
# Find packages
find_package(Threads REQUIRED)
find_package(Boost 1.75 REQUIRED COMPONENTS system filesystem)
# Add executable
add_executable(myapp
src/main.cpp
src/module.cpp
include/module.h
)
# Include directories
target_include_directories(myapp PRIVATE include)
# Link libraries
target_link_libraries(myapp PRIVATE
Threads::Threads
Boost::system
Boost::filesystem
)
# Install
install(TARGETS myapp DESTINATION bin)
Anti-Patterns to Avoid
❌ Raw pointers for ownership: Use smart pointers
❌ Manual memory management: Use RAII
❌ Using C-style arrays: Use std::array or std::vector
❌ Ignoring const correctness: Mark everything const that can be
❌ Unnecessary copies: Use move semantics and references
❌ Premature optimization: Profile before optimizing
❌ Using new without delete: Use smart pointers
Reference Documentation
Detailed material lives alongside this skill and is read on demand:
- Best Practices — RAII, Const Correctness, Rule of Zero/Three/Five
- Modern C++ Syntax — Concepts (C++20), Ranges and Views (C++20), Coroutines (C++20), Smart Pointers, Move Semantics, Templates and Metaprogramming, std::format (C++20)
Resources
1---
2name: cpp-expert
3version: 1.1.0
4description: >-
5 Expert-level C++ development with modern C++20/23, STL, memory management, and
6 performance. Use when the user mentions C++, C++20, C++23, the STL, templates, or
7 performance, or when the task involves Modern C++ Features, Memory Management, Ranges and
8 Views, or Coroutines.
9category: languages
10tags: [cpp, c++, c++20, c++23, stl, templates, performance, memory]
11allowed-tools:
12 - Read
13 - Write
14 - Edit
15 - Bash(g++:*, clang++:*, cmake:*, make:*)
16metadata:
17 source: https://skillmd.com/skills/personamanagmentlayer/cpp-expert
18---
19
20# C++ Expert
21
22Expert guidance for modern C++ development including C++20/23 features, STL, templates, memory management, and high-performance programming.
23
24## Core Concepts
25
26### Modern C++ Features (C++20/23)
27
28- Concepts and constraints
29- Ranges and views
30- Coroutines
31- Modules
32- Three-way comparison (spaceship operator)
33- std::format
34- std::span
35- Designated initializers
36- consteval and constinit
37
38### Memory Management
39
40- RAII (Resource Acquisition Is Initialization)
41- Smart pointers (unique_ptr, shared_ptr, weak_ptr)
42- Move semantics and perfect forwarding
43- Memory allocation strategies
44- Custom allocators
45- Memory pools
46
47### Performance
48
49- Zero-cost abstractions
50- Inline optimization
51- Template metaprogramming
52- Compile-time computation (constexpr)
53- Cache-friendly data structures
54- SIMD operations
55
56## STL Containers
57
58### Sequential Containers
59
60```cpp
61#include <vector>
62#include <deque>
63#include <list>
64#include <array>
65
66// vector - dynamic array
67std::vector<int> vec = {1, 2, 3, 4, 5};
68vec.push_back(6);
69vec.emplace_back(7); // Construct in-place
70vec.reserve(100); // Pre-allocate capacity
71
72// deque - double-ended queue
73std::deque<int> deq = {1, 2, 3};
74deq.push_front(0);
75deq.push_back(4);
76
77// list - doubly-linked list
78std::list<int> lst = {1, 2, 3};
79lst.push_front(0);
80lst.push_back(4);
81lst.remove(2); // Remove all elements with value 2
82
83// array - fixed-size array
84std::array<int, 5> arr = {1, 2, 3, 4, 5};
85```
86
87### Associative Containers
88
89```cpp
90#include <map>
91#include <set>
92#include <unordered_map>
93#include <unordered_set>
94
95// map - ordered key-value pairs
96std::map<std::string, int> ages;
97ages["Alice"] = 30;
98ages["Bob"] = 25;
99ages.insert({"Charlie", 35});
100
101// set - ordered unique elements
102std::set<int> numbers = {3, 1, 4, 1, 5, 9};
103numbers.insert(2);
104
105// unordered_map - hash table
106std::unordered_map<std::string, int> hash_map;
107hash_map["key"] = 42;
108
109// unordered_set - hash set
110std::unordered_set<int> hash_set = {1, 2, 3};
111```
112
113## Algorithms
114
115```cpp
116#include <algorithm>
117#include <numeric>
118#include <vector>
119
120std::vector<int> numbers = {5, 2, 8, 1, 9, 3, 7};
121
122// Sorting
123std::sort(numbers.begin(), numbers.end());
124std::sort(numbers.begin(), numbers.end(), std::greater<int>());
125
126// Searching
127auto it = std::find(numbers.begin(), numbers.end(), 8);
128bool found = std::binary_search(numbers.begin(), numbers.end(), 5);
129
130// Transforming
131std::vector<int> doubled(numbers.size());
132std::transform(numbers.begin(), numbers.end(), doubled.begin(),
133 [](int n) { return n * 2; });
134
135// Filtering
136std::vector<int> evens;
137std::copy_if(numbers.begin(), numbers.end(), std::back_inserter(evens),
138 [](int n) { return n % 2 == 0; });
139
140// Accumulate
141int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
142int product = std::accumulate(numbers.begin(), numbers.end(), 1,
143 std::multiplies<int>());
144
145// Partition
146auto pivot = std::partition(numbers.begin(), numbers.end(),
147 [](int n) { return n < 5; });
148
149// Remove
150numbers.erase(std::remove(numbers.begin(), numbers.end(), 5), numbers.end());
151
152// Unique (remove consecutive duplicates)
153std::sort(numbers.begin(), numbers.end());
154numbers.erase(std::unique(numbers.begin(), numbers.end()), numbers.end());
155```
156
157## Concurrency
158
159```cpp
160#include <thread>
161#include <mutex>
162#include <future>
163#include <atomic>
164
165// Thread
166void worker(int id) {
167 std::cout << "Thread " << id << '\n';
168}
169
170std::thread t1(worker, 1);
171std::thread t2(worker, 2);
172t1.join();
173t2.join();
174
175// Mutex
176std::mutex mtx;
177int shared_data = 0;
178
179void increment() {
180 std::lock_guard<std::mutex> lock(mtx);
181 ++shared_data;
182}
183
184// Atomic
185std::atomic<int> counter{0};
186counter++; // Thread-safe
187counter.fetch_add(5);
188
189// Future and promise
190std::promise<int> prom;
191std::future<int> fut = prom.get_future();
192
193std::thread t([&prom]() {
194 std::this_thread::sleep_for(std::chrono::seconds(1));
195 prom.set_value(42);
196});
197
198int result = fut.get(); // Blocks until ready
199t.join();
200
201// async
202auto future = std::async(std::launch::async, []() {
203 return 42;
204});
205
206int value = future.get();
207```
208
209## Build Systems
210
211### CMake
212
213```cmake
214# CMakeLists.txt
215cmake_minimum_required(VERSION 3.20)
216project(MyApp VERSION 1.0.0 LANGUAGES CXX)
217
218# Set C++ standard
219set(CMAKE_CXX_STANDARD 20)
220set(CMAKE_CXX_STANDARD_REQUIRED ON)
221
222# Compiler flags
223if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
224 add_compile_options(-Wall -Wextra -Wpedantic -O3)
225endif()
226
227# Find packages
228find_package(Threads REQUIRED)
229find_package(Boost 1.75 REQUIRED COMPONENTS system filesystem)
230
231# Add executable
232add_executable(myapp
233 src/main.cpp
234 src/module.cpp
235 include/module.h
236)
237
238# Include directories
239target_include_directories(myapp PRIVATE include)
240
241# Link libraries
242target_link_libraries(myapp PRIVATE
243 Threads::Threads
244 Boost::system
245 Boost::filesystem
246)
247
248# Install
249install(TARGETS myapp DESTINATION bin)
250```
251
252## Anti-Patterns to Avoid
253
254❌ **Raw pointers for ownership**: Use smart pointers
255❌ **Manual memory management**: Use RAII
256❌ **Using C-style arrays**: Use std::array or std::vector
257❌ **Ignoring const correctness**: Mark everything const that can be
258❌ **Unnecessary copies**: Use move semantics and references
259❌ **Premature optimization**: Profile before optimizing
260❌ **Using `new` without `delete`**: Use smart pointers
261
262## Reference Documentation
263
264Detailed material lives alongside this skill and is read on demand:
265
266- [Best Practices](references/BEST_PRACTICES.md) — RAII, Const Correctness, Rule of Zero/Three/Five
267- [Modern C++ Syntax](references/MODERN_C_SYNTAX.md) — Concepts (C++20), Ranges and Views (C++20), Coroutines (C++20), Smart Pointers, Move Semantics, Templates and Metaprogramming, std::format (C++20)
268
269## Resources
270
271- C++ Reference: https://en.cppreference.com/
272- C++ Core Guidelines: https://isocpp.github.io/CppCoreGuidelines/
273- Compiler Explorer: https://godbolt.org/
274- CPP Reference: https://cplusplus.com/