
custom-plugin-cpp
Complete C++ Programming System - Learn AND Develop with expert AI agents. Master fundamentals, OOP, STL, and modern C++. Hybrid learning + development workflow.
- version
- 2.0.0
- GitHub stars
- 7
Install
/plugin install custom-plugin-cpp@pluginagentmarketplace-cppRun it inside Claude Code after adding the marketplace with /plugin marketplace add pluginagentmarketplace/custom-plugin-cpp.
Contents
Discovered from sourceSkills 9
Algorithms Skill
Production-Grade Learning Skill | Algorithms & Data Structures
Master algorithm design and implementation in C++ with complexity analysis.
Complexity Analysis
Big O Notation Reference
| Complexity | Name | Example | Operations (n=1000) |
|---|---|---|---|
| O(1) | Constant | Array access | 1 |
| O(log n) | Logarithmic | Binary search | 10 |
| O(n) | Linear | Linear search | 1,000 |
| O(n log n) | Linearithmic | Merge sort | 10,000 |
| O(n²) | Quadratic | Bubble sort | 1,000,000 |
| O(2^n) | Exponential | Recursive fib | 10^301 |
Complexity Analysis Framework
// Time Complexity Analysis Template
// 1. Count primitive operations
// 2. Express as function of input size n
// 3. Keep highest order term
// 4. Drop constants
// Example: Find maximum
int findMax(const std::vector<int>& v) { // O(n)
int max = v[0]; // O(1)
for (int i = 1; i < v.size(); ++i) { // O(n) iterations
if (v[i] > max) { // O(1)
max = v[i]; // O(1)
}
}
return max; // O(1)
} // Total: O(1) + O(n) * O(1) = O(n)
Sorting Algorithms
STL Sorting
#include <algorithm>
#include <vector>
std::vector<int> v = {5, 2, 8, 1, 9};
// Introsort - O(n log n) guaranteed
std::sort(v.begin(), v.end());
// Stable sort - preserves relative order of equal elements
std::stable_sort(v.begin(), v.end());
// Partial sort - only first k elements sorted
std::partial_sort(v.begin(), v.begin() + 3, v.end());
// Nth element - partition around nth element (O(n) average)
std::nth_element(v.begin(), v.begin() + v.size()/2, v.end());
// Custom comparator (descending order)
std::sort(v.begin(), v.end(), std::greater<int>());
// Sort by projection (C++20)
std::ranges::sort(v, {}, [](int x) { return std::abs(x); });
Sorting Algorithm Comparison
| Algorithm | Best | Average | Worst | Space | Stable |
|---|---|---|---|---|---|
| Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Tim Sort | O(n) | O(n log n) | O(n log n) | O(n) | Yes |
Searching Algorithms
Binary Search
#include <algorithm>
// STL binary search - O(log n), requires sorted range
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// Check existence
bool found = std::binary_search(v.begin(), v.end(), 5);
// Find position
auto it = std::lower_bound(v.begin(), v.end(), 5); // First >= 5
auto it2 = std::upper_bound(v.begin(), v.end(), 5); // First > 5
// Range of equal elements
auto [lo, hi] = std::equal_range(v.begin(), v.end(), 5);
// Custom binary search with predicate
template<typename T, typename Pred>
T binary_search_first_true(T lo, T hi, Pred pred) {
while (lo < hi) {
T mid = lo + (hi - lo) / 2;
if (pred(mid)) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}
Graph Algorithms
Graph Representations
// Adjacency List (preferred for sparse graphs)
std::vector<std::vector<int>> adj(n);
adj[0].push_back(1); // Edge 0 -> 1
// Adjacency List with weights
std::vector<std::vector<std::pair<int, int>>> adj(n);
adj[0].push_back({1, weight}); // Edge 0 -> 1 with weight
// Adjacency Matrix (for dense graphs)
std::vector<std::vector<int>> adj(n, std::vector<int>(n, 0));
adj[0][1] = 1; // Edge 0 -> 1
BFS - Breadth First Search
std::vector<int> bfs(int start, const std::vector<std::vector<int>>& adj) {
std::vector<int> dist(adj.size(), -1);
std::queue<int> q;
dist[start] = 0;
q.push(start);
while (!q.empty()) {
int node = q.front();
q.pop();
for (int neighbor : adj[node]) {
if (dist[neighbor] == -1) {
dist[neighbor] = dist[node] + 1;
q.push(neighbor);
}
}
}
return dist; // Shortest distances from start
}
DFS - Depth First Search
void dfs(int node, const std::vector<std::vector<int>>& adj,
std::vector<bool>& visited, std::vector<int>& result) {
visited[node] = true;
result.push_back(node);
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
dfs(neighbor, adj, visited, result);
}
}
}
Dijkstra's Algorithm
std::vector<int> dijkstra(int start,
const std::vector<std::vector<std::pair<int,int>>>& adj) {
std::vector<int> dist(adj.size(), INT_MAX);
std::priority_queue<std::pair<int,int>,
std::vector<std::pair<int,int>>,
std::greater<>> pq;
dist[start] = 0;
pq.push({0, start});
while (!pq.empty()) {
auto [d, u] = pq.top();
pq.pop();
if (d > dist[u]) continue; // Skip outdated entries
for (auto [v, w] : adj[u]) {
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
pq.push({dist[v], v});
}
}
}
return dist;
}
Dynamic Programming
DP Framework
// 1. Define state: What subproblem does dp[i] represent?
// 2. Define transition: How to compute dp[i] from previous states?
// 3. Define base case: What are the initial values?
// 4. Define answer: Which state(s) give the final answer?
// Example: Longest Increasing Subsequence
int lis(const std::vector<int>& nums) {
int n = nums.size();
std::vector<int> dp(n, 1); // dp[i] = LIS ending at i
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (nums[j] < nums[i]) {
dp[i] = std::max(dp[i], dp[j] + 1);
}
}
}
return *std::max_element(dp.begin(), dp.end());
}
// Optimized LIS with binary search - O(n log n)
int lisOptimized(const std::vector<int>& nums) {
std::vector<int> tails;
for (int x : nums) {
auto it = std::lower_bound(tails.begin(), tails.end(), x);
if (it == tails.end()) {
tails.push_back(x);
} else {
*it = x;
}
}
return tails.size();
}
Common DP Patterns
| Pattern | Example | State | Complexity |
|---|---|---|---|
| Linear | Fibonacci | dp[i] | O(n) |
| 2D Grid | Path count | dp[i][j] | O(n×m) |
| Interval | Matrix chain | dp[i][j] | O(n³) |
| Subset | Knapsack | dp[mask] | O(2^n) |
| Tree | Tree DP | dp[node] | O(n) |
Algorithm Selection Flowchart
What type of problem?
├── Searching
│ ├── Sorted data? → Binary Search O(log n)
│ └── Unsorted? → Linear Search O(n) or Hash O(1)
├── Sorting
│ ├── Need stable? → std::stable_sort
│ ├── Partial sort? → std::partial_sort
│ └── General? → std::sort
├── Optimization
│ ├── Overlapping subproblems? → Dynamic Programming
│ └── Greedy choice property? → Greedy Algorithm
├── Graph
│ ├── Shortest path (unweighted)? → BFS
│ ├── Shortest path (weighted)? → Dijkstra/Bellman-Ford
│ ├── All pairs shortest? → Floyd-Warshall
│ └── Minimum spanning tree? → Kruskal/Prim
└── String
├── Pattern matching? → KMP/Rabin-Karp
└── Longest common? → DP
Troubleshooting Decision Tree
Algorithm not working correctly?
├── Wrong output
│ ├── Check base cases
│ ├── Verify loop bounds
│ ├── Test edge cases (empty, single element)
│ └── Print intermediate values
├── Time Limit Exceeded (TLE)
│ ├── Check complexity matches constraint
│ ├── Look for unnecessary recomputation
│ ├── Consider memoization/DP
│ └── Use better data structure
├── Memory Limit Exceeded (MLE)
│ ├── Reduce DP state dimensions
│ ├── Use rolling array technique
│ └── Clear visited sets between runs
└── Runtime Error
├── Check array bounds
├── Check integer overflow
└── Check stack overflow (recursion depth)
Unit Test Template
#include <gtest/gtest.h>
#include "algorithms.hpp"
class AlgorithmTest : public ::testing::Test {
protected:
void SetUp() override {
sorted_vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
unsorted_vec = {5, 2, 8, 1, 9, 3, 7, 4, 6, 10};
}
std::vector<int> sorted_vec;
std::vector<int> unsorted_vec;
};
TEST_F(AlgorithmTest, BinarySearchFindsElement) {
EXPECT_TRUE(std::binary_search(sorted_vec.begin(), sorted_vec.end(), 5));
EXPECT_FALSE(std::binary_search(sorted_vec.begin(), sorted_vec.end(), 11));
}
TEST_F(AlgorithmTest, SortProducesOrderedOutput) {
std::sort(unsorted_vec.begin(), unsorted_vec.end());
EXPECT_TRUE(std::is_sorted(unsorted_vec.begin(), unsorted_vec.end()));
}
TEST_F(AlgorithmTest, BFSFindsShortestPath) {
std::vector<std::vector<int>> adj = {{1, 2}, {0, 3}, {0, 3}, {1, 2}};
auto dist = bfs(0, adj);
EXPECT_EQ(dist[0], 0);
EXPECT_EQ(dist[1], 1);
EXPECT_EQ(dist[3], 2);
}
TEST_F(AlgorithmTest, LISHandlesEdgeCases) {
EXPECT_EQ(lis({}), 0);
EXPECT_EQ(lis({1}), 1);
EXPECT_EQ(lis({3, 2, 1}), 1); // Decreasing
EXPECT_EQ(lis({1, 2, 3}), 3); // Increasing
}
Integration Points
| Component | Interface |
|---|---|
stl-master | Container selection |
performance-optimizer | Algorithm optimization |
modern-cpp-expert | Ranges and concepts |
cpp-fundamentals-agent | Basic concepts |
C++ Plugin v3.0.0 - Production-Grade Learning Skill
Build Systems Skill
Production-Grade Development Skill | C++ Build Infrastructure
Master C++ build systems, package management, and CI/CD integration.
Modern CMake Patterns
Project Structure
# CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(MyProject
VERSION 1.0.0
DESCRIPTION "A modern C++ project"
LANGUAGES CXX
)
# ────────────────────────────────────────────────────────────────
# Global Settings
# ────────────────────────────────────────────────────────────────
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# ────────────────────────────────────────────────────────────────
# Options
# ────────────────────────────────────────────────────────────────
option(BUILD_TESTING "Build unit tests" ON)
option(BUILD_DOCS "Build documentation" OFF)
option(ENABLE_SANITIZERS "Enable sanitizers in debug builds" ON)
option(ENABLE_COVERAGE "Enable code coverage" OFF)
# ────────────────────────────────────────────────────────────────
# Compiler Warnings Interface
# ────────────────────────────────────────────────────────────────
add_library(project_warnings INTERFACE)
target_compile_options(project_warnings INTERFACE
$<$<CXX_COMPILER_ID:GNU,Clang>:
-Wall -Wextra -Wpedantic -Werror
-Wshadow -Wnon-virtual-dtor -Wcast-align
-Wunused -Woverloaded-virtual -Wconversion
>
$<$<CXX_COMPILER_ID:MSVC>:
/W4 /WX /permissive-
>
)
# ────────────────────────────────────────────────────────────────
# Sanitizers (Debug builds)
# ────────────────────────────────────────────────────────────────
add_library(project_sanitizers INTERFACE)
if(ENABLE_SANITIZERS AND CMAKE_BUILD_TYPE STREQUAL "Debug")
target_compile_options(project_sanitizers INTERFACE
-fsanitize=address,undefined
-fno-omit-frame-pointer
)
target_link_options(project_sanitizers INTERFACE
-fsanitize=address,undefined
)
endif()
Target-Based CMake
# Library target
add_library(mylib
src/core.cpp
src/utils.cpp
)
target_include_directories(mylib
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src
)
target_link_libraries(mylib
PUBLIC fmt::fmt
PRIVATE project_warnings project_sanitizers
)
# Executable target
add_executable(myapp src/main.cpp)
target_link_libraries(myapp PRIVATE mylib project_warnings)
Dependency Management
FetchContent (CMake 3.14+)
include(FetchContent)
FetchContent_Declare(
fmt
GIT_REPOSITORY https://github.com/fmtlib/fmt.git
GIT_TAG 10.2.1
GIT_SHALLOW TRUE
)
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG v1.14.0
)
FetchContent_MakeAvailable(fmt googletest)
target_link_libraries(mylib PRIVATE fmt::fmt)
target_link_libraries(mytest PRIVATE GTest::gtest_main)
Conan 2.x
# conanfile.py
from conan import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake, cmake_layout
class MyProjectConan(ConanFile):
name = "myproject"
version = "1.0.0"
settings = "os", "compiler", "build_type", "arch"
requires = [
"fmt/10.2.1",
"spdlog/1.13.0",
"nlohmann_json/3.11.3"
]
generators = "CMakeDeps"
def layout(self):
cmake_layout(self)
def generate(self):
tc = CMakeToolchain(self)
tc.generate()
def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()
def package(self):
cmake = CMake(self)
cmake.install()
# Build with Conan
conan install . --output-folder=build --build=missing
cmake -B build -DCMAKE_TOOLCHAIN_FILE=build/conan_toolchain.cmake
cmake --build build
vcpkg
// vcpkg.json (manifest mode)
{
"name": "myproject",
"version": "1.0.0",
"dependencies": [
"fmt",
"spdlog",
{
"name": "boost-filesystem",
"platform": "!windows"
},
{
"name": "gtest",
"features": ["gmock"]
}
]
}
# Build with vcpkg
cmake -B build \
-DCMAKE_TOOLCHAIN_FILE=$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake
cmake --build build
Cross-Platform Builds
Toolchain Files
# toolchain/linux-clang.cmake
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_C_COMPILER clang)
set(CMAKE_CXX_COMPILER clang++)
# toolchain/windows-mingw.cmake
set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc)
set(CMAKE_CXX_COMPILER x86_64-w64-mingw32-g++)
set(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres)
# Usage
cmake -B build -DCMAKE_TOOLCHAIN_FILE=toolchain/linux-clang.cmake
Platform-Specific Code
# Detect platform
if(WIN32)
target_compile_definitions(mylib PUBLIC PLATFORM_WINDOWS)
target_sources(mylib PRIVATE src/platform/windows.cpp)
elseif(APPLE)
target_compile_definitions(mylib PUBLIC PLATFORM_MACOS)
target_sources(mylib PRIVATE src/platform/macos.cpp)
else()
target_compile_definitions(mylib PUBLIC PLATFORM_LINUX)
target_sources(mylib PRIVATE src/platform/linux.cpp)
endif()
CI/CD Configuration
GitHub Actions
# .github/workflows/ci.yml
name: CI
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
build:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
build_type: [Debug, Release]
compiler:
- { cc: gcc, cxx: g++ }
- { cc: clang, cxx: clang++ }
exclude:
- os: windows-latest
compiler: { cc: gcc, cxx: g++ }
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- name: Install dependencies (Ubuntu)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y ninja-build lcov
- name: Configure
run: |
cmake -B build \
-G Ninja \
-DCMAKE_BUILD_TYPE=${{ matrix.build_type }} \
-DCMAKE_C_COMPILER=${{ matrix.compiler.cc }} \
-DCMAKE_CXX_COMPILER=${{ matrix.compiler.cxx }} \
-DBUILD_TESTING=ON
- name: Build
run: cmake --build build --parallel
- name: Test
run: ctest --test-dir build --output-on-failure --parallel
- name: Upload coverage
if: matrix.build_type == 'Debug' && matrix.os == 'ubuntu-latest'
uses: codecov/codecov-action@v3
GitLab CI
# .gitlab-ci.yml
stages:
- build
- test
- deploy
variables:
GIT_SUBMODULE_STRATEGY: recursive
.build_template: &build_template
stage: build
script:
- cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=${BUILD_TYPE}
- cmake --build build --parallel
artifacts:
paths:
- build/
build:debug:
<<: *build_template
variables:
BUILD_TYPE: Debug
build:release:
<<: *build_template
variables:
BUILD_TYPE: Release
test:
stage: test
needs: [build:debug]
script:
- ctest --test-dir build --output-on-failure
Compiler Flags Reference
| Purpose | GCC/Clang | MSVC |
|---|---|---|
| C++20 Standard | -std=c++20 | /std:c++20 |
| Optimize (Release) | -O2, -O3 | /O2 |
| Debug info | -g | /Zi |
| No optimization | -O0 | /Od |
| Warnings | -Wall -Wextra | /W4 |
| Errors on warnings | -Werror | /WX |
| AddressSanitizer | -fsanitize=address | /fsanitize=address |
| Link-time optimization | -flto | /GL, /LTCG |
| Position independent | -fPIC | (default) |
| Native CPU | -march=native | /arch:AVX2 |
Build Workflow
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ CONFIGURE │───▶│ BUILD │───▶│ TEST │
│ (cmake) │ │ (ninja) │ │ (ctest) │
└─────────────┘ └──────────────┘ └───────────────┘
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ INSTALL │◀───│ PACKAGE │◀───│ DEPLOY │
│ (targets) │ │ (cpack) │ │ (ci/cd) │
└─────────────┘ └──────────────┘ └───────────────┘
Troubleshooting Decision Tree
Build error?
├── CMake configuration failed
│ ├── "Could not find package" → Check CMAKE_PREFIX_PATH
│ ├── "Unknown CMake command" → Upgrade CMake version
│ └── "Compiler not found" → Install compiler or set CC/CXX
├── Compilation failed
│ ├── Missing header → Add target_include_directories
│ ├── Syntax error → Check C++ standard flag
│ └── Undefined macro → Add target_compile_definitions
├── Linking failed
│ ├── "undefined reference" → Add target_link_libraries
│ ├── "multiple definition" → Check ODR violations
│ └── "cannot find -lxxx" → Add library path
└── Runtime error
├── "library not found" → Check LD_LIBRARY_PATH
└── "symbol not found" → ABI mismatch, rebuild all
Common Build Errors
| Error | Cause | Solution |
|---|---|---|
undefined reference to | Missing library link | Add target_link_libraries |
file not found | Wrong include path | Check target_include_directories |
CMake version too low | Old CMake | Upgrade or lower cmake_minimum_required |
ABI incompatibility | Mixed compiler versions | Use consistent toolchain |
multiple definition | Header with implementation | Use inline or move to .cpp |
Unit Test Template
#include <gtest/gtest.h>
// Test that build configuration works
TEST(BuildSystemTest, CompilerFeatures) {
// Verify C++ standard
#if __cplusplus >= 202002L
SUCCEED() << "C++20 or later";
#else
FAIL() << "Expected C++20 or later";
#endif
}
TEST(BuildSystemTest, PlatformMacros) {
#if defined(PLATFORM_WINDOWS)
EXPECT_TRUE(true) << "Windows build";
#elif defined(PLATFORM_LINUX)
EXPECT_TRUE(true) << "Linux build";
#elif defined(PLATFORM_MACOS)
EXPECT_TRUE(true) << "macOS build";
#else
FAIL() << "Unknown platform";
#endif
}
TEST(BuildSystemTest, DebugRelease) {
#ifdef NDEBUG
EXPECT_TRUE(true) << "Release build";
#else
EXPECT_TRUE(true) << "Debug build";
#endif
}
Integration Points
| Component | Interface |
|---|---|
performance-optimizer | Optimization flags |
cpp-debugger-agent | Debug build config |
modern-cpp-expert | C++ standard flags |
memory-specialist | Sanitizer configuration |
C++ Plugin v3.0.0 - Production-Grade Development Skill
C++ Basics Skill
Production-Grade Learning Skill | Foundation Building
Master the essential building blocks of C++ programming.
Topics Covered
1. Variables & Data Types
#include <iostream>
#include <cstdint> // Fixed-width integers
int main() {
// ─────────────────────────────────────────────────
// Integer Types (with guaranteed sizes)
// ─────────────────────────────────────────────────
int8_t tiny = 127; // 1 byte, -128 to 127
int16_t small = 32767; // 2 bytes
int32_t normal = 2147483647; // 4 bytes
int64_t large = 9223372036854775807; // 8 bytes
// Unsigned variants
uint8_t ubyte = 255; // 0 to 255
uint32_t ucount = 4294967295; // 0 to 4B
// ─────────────────────────────────────────────────
// Floating Point
// ─────────────────────────────────────────────────
float f = 3.14f; // ~7 decimal digits
double d = 3.14159265358979; // ~15 decimal digits
// ─────────────────────────────────────────────────
// Character & Boolean
// ─────────────────────────────────────────────────
char c = 'A'; // ASCII character
bool b = true; // true or false
// ─────────────────────────────────────────────────
// Modern C++ Initialization (prefer brace init)
// ─────────────────────────────────────────────────
int x{42}; // Brace initialization
auto y = 3.14; // Type deduction (double)
auto z{10}; // int
return 0;
}
2. Operators
| Category | Operators | Example |
|---|---|---|
| Arithmetic | + - * / % | 10 / 3 = 3 |
| Comparison | == != < > <= >= | 5 == 5 → true |
| Logical | && || ! | true && false → false |
| Bitwise | & | ^ ~ << >> | 0xFF & 0x0F → 0x0F |
| Assignment | = += -= *= /= | x += 5 |
| Increment | ++ -- | ++i (prefer prefix) |
3. Control Flow
// ─────────────────────────────────────────────────────
// Conditionals
// ─────────────────────────────────────────────────────
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else {
grade = 'F';
}
// Switch with C++17 init
switch (int x = getValue(); x) {
case 1: std::cout << "One\n"; break;
case 2: std::cout << "Two\n"; break;
default: std::cout << "Other\n"; break;
}
// ─────────────────────────────────────────────────────
// Loops
// ─────────────────────────────────────────────────────
// For loop (prefer prefix ++)
for (int i = 0; i < n; ++i) { }
// Range-based for (C++11)
for (const auto& item : container) { }
// While
while (condition) { }
// Do-while (runs at least once)
do { } while (condition);
4. Functions
// ─────────────────────────────────────────────────────
// Function declaration
// ─────────────────────────────────────────────────────
int add(int a, int b); // Declaration
void greet(std::string_view name); // string_view for efficiency
// ─────────────────────────────────────────────────────
// Definition with default parameter
// ─────────────────────────────────────────────────────
int add(int a, int b) {
return a + b;
}
void greet(std::string_view name = "World") {
std::cout << "Hello, " << name << "!\n";
}
// ─────────────────────────────────────────────────────
// Pass by reference (for modification or large objects)
// ─────────────────────────────────────────────────────
void increment(int& value) {
++value;
}
void process(const std::vector<int>& data) { // const ref for read-only
for (int x : data) { /* ... */ }
}
// ─────────────────────────────────────────────────────
// Function overloading
// ─────────────────────────────────────────────────────
int max(int a, int b) { return (a > b) ? a : b; }
double max(double a, double b) { return (a > b) ? a : b; }
Troubleshooting
Common Errors
| Error | Cause | Fix |
|---|---|---|
undefined reference | Missing function definition | Add function body |
expected ';' | Missing semicolon | Check previous line |
undeclared identifier | Variable not declared | Declare before use |
narrowing conversion | Data loss in brace init | Use explicit cast |
Decision Tree
Compilation error?
├── "undefined reference"
│ └── Function declared but not defined → Add definition
├── "expected ';'"
│ └── Missing semicolon → Check line above error
├── "undeclared identifier"
│ └── Variable not in scope → Declare or check spelling
└── "no matching function"
└── Wrong argument types → Match function signature
Unit Test Template
#include <cassert>
void test_basics() {
// Test integer operations
assert(add(2, 3) == 5);
assert(add(-1, 1) == 0);
// Test floating point (with tolerance)
constexpr double epsilon = 1e-9;
assert(std::abs(calculateArea(2.0) - 12.566370614) < epsilon);
// Test boolean logic
assert((true && false) == false);
assert((true || false) == true);
std::cout << "All tests passed!\n";
}
Learning Path
Week 1: Foundation
├── Day 1-2: Variables & data types
├── Day 3-4: Operators
├── Day 5-6: Control flow
└── Day 7: Practice exercises
Week 2: Functions & Arrays
├── Day 1-2: Functions basics
├── Day 3-4: Arrays & pointers
├── Day 5-6: String handling
└── Day 7: Mini project
References
C++ Plugin v3.0.0 - Production-Grade Learning Skill
Debugging Skill
Production-Grade Development Skill | C++ Debugging & Error Analysis
Master C++ debugging tools and systematic investigation techniques.
Debugging Workflow
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ REPRODUCE │───▶│ ISOLATE │───▶│ INSTRUMENT │
│ (confirm) │ │ (minimize) │ │ (observe) │
└─────────────┘ └──────────────┘ └───────────────┘
│ │
▼ ▼
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ VERIFY │◀───│ FIX │◀───│ ANALYZE │
│ (test) │ │ (correct) │ │ (root cause) │
└─────────────┘ └──────────────┘ └───────────────┘
GDB (GNU Debugger)
Essential Commands
# Compile with debug symbols
g++ -g -O0 program.cpp -o program
# Start GDB
gdb ./program
# Core dump analysis
gdb ./program core.dump
# Execution Control
run [args] # Start program
continue (c) # Continue execution
next (n) # Step over
step (s) # Step into
finish # Run until current function returns
until <line> # Run until line
# Breakpoints
break main # Break at function
break file.cpp:42 # Break at line
break *0x400520 # Break at address
break func if x > 5 # Conditional breakpoint
delete <num> # Remove breakpoint
disable/enable <num> # Toggle breakpoint
# Inspection
print variable # Print value
print/x variable # Print in hex
display variable # Print at each stop
info locals # Show local variables
info args # Show function arguments
ptype variable # Show type
# Stack Navigation
backtrace (bt) # Show call stack
frame <n> # Select frame
up/down # Move in stack
# Memory
x/10xw 0x400520 # Examine 10 words in hex
watch variable # Break when variable changes
rwatch variable # Break when variable is read
# Advanced
catch throw # Break on exception
set variable x = 5 # Modify variable
call func(args) # Call function
GDB Scripts
# .gdbinit - Auto-loaded configuration
set history save on
set print pretty on
set print array on
set pagination off
# Custom command
define pv
print *$arg0@$arg1
end
# Usage: pv array 10
LLDB (macOS/Clang)
# Start LLDB
lldb ./program
# Attach to process
lldb -p <pid>
# Breakpoints
breakpoint set --name main
breakpoint set --file main.cpp --line 42
breakpoint set --method MyClass::method
# Execution
run
continue
next
step
finish
# Inspection
frame variable # Show all locals
frame variable varname # Show specific variable
expression varname # Evaluate expression
expression -O -- object # Print object description
# Stack
thread backtrace
frame select <n>
up/down
# Watchpoints
watchpoint set variable varname
watchpoint set expression -- &array[5]
Sanitizers
AddressSanitizer (ASan)
# Compile with ASan
g++ -fsanitize=address -g -O1 program.cpp -o program
# Run (ASan is active)
./program
# Detects:
# - Heap buffer overflow
# - Stack buffer overflow
# - Global buffer overflow
# - Use after free
# - Use after return
# - Double free
# - Memory leaks (with ASAN_OPTIONS=detect_leaks=1)
UndefinedBehaviorSanitizer (UBSan)
# Compile with UBSan
g++ -fsanitize=undefined -g program.cpp -o program
# Detects:
# - Signed integer overflow
# - Division by zero
# - Null pointer dereference
# - Invalid shift
# - Out-of-bounds array access
# - Misaligned pointer access
ThreadSanitizer (TSan)
# Compile with TSan
g++ -fsanitize=thread -g program.cpp -o program
# Detects:
# - Data races
# - Deadlocks (with deadlock_detector=1)
# - Lock order violations
Combined Usage
# CMakeLists.txt
option(ENABLE_SANITIZERS "Enable sanitizers" OFF)
if(ENABLE_SANITIZERS)
add_compile_options(
-fsanitize=address,undefined
-fno-omit-frame-pointer
-g
)
add_link_options(
-fsanitize=address,undefined
)
endif()
Valgrind
Memory Leak Detection
# Check for memory leaks
valgrind --leak-check=full --show-leak-kinds=all ./program
# With line numbers
valgrind --leak-check=full --track-origins=yes ./program
# Generate suppressions for known issues
valgrind --gen-suppressions=all ./program
Memcheck Options
valgrind --tool=memcheck \
--leak-check=full \
--show-leak-kinds=all \
--track-origins=yes \
--verbose \
--log-file=valgrind.log \
./program
Cachegrind (Cache Profiling)
valgrind --tool=cachegrind ./program
cg_annotate cachegrind.out.*
# Output shows:
# - I1 cache read misses
# - D1 cache read/write misses
# - LL (last level) cache misses
Common Issue Patterns
Issue Diagnostic Table
| Issue | Symptoms | Primary Tool | Secondary Tool |
|---|---|---|---|
| Segfault | SIGSEGV, crash | GDB + bt | ASan |
| Memory leak | Growing memory | Valgrind | ASan (leak check) |
| Buffer overflow | Corruption, crash | ASan | Valgrind |
| Use after free | Random crash | ASan | Valgrind |
| Data race | Random behavior | TSan | Helgrind |
| Deadlock | Hang | GDB + threads | TSan |
| Integer overflow | Wrong results | UBSan | - |
| Null deref | Crash at low address | ASan | GDB |
| Stack overflow | Deep recursion crash | GDB | ulimit |
Quick Diagnosis Commands
# Check if crash is reproducible
for i in {1..100}; do ./program || echo "Crashed on run $i"; done
# Get core dump
ulimit -c unlimited
./program # Will generate core file
# Quick stack trace from core
gdb -batch -ex "bt" ./program core
# Check for memory issues quickly
MALLOC_CHECK_=3 ./program
Troubleshooting Decision Tree
Program crashed?
├── Segmentation fault (SIGSEGV)
│ ├── Get backtrace: gdb -batch -ex "bt" ./program core
│ ├── Check for NULL deref: look at crash address
│ ├── Check for buffer overflow: run with ASan
│ └── Check for use-after-free: run with ASan
├── Abort (SIGABRT)
│ ├── Check assert failures: look at stderr
│ ├── Check std::terminate: uncaught exception
│ └── Check double free: run with ASan
├── Hang (no progress)
│ ├── Attach debugger: gdb -p <pid>
│ ├── Check for deadlock: info threads, thread apply all bt
│ └── Check for infinite loop: break, bt
└── Wrong output
├── Check undefined behavior: run with UBSan
├── Add logging at key points
└── Use debugger to trace execution
Debug Build Configuration
# CMakeLists.txt
set(CMAKE_BUILD_TYPE Debug)
# Ensure debug symbols
set(CMAKE_CXX_FLAGS_DEBUG "-g -O0")
# Sanitizers for debug builds
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
add_compile_options(-fsanitize=address,undefined)
add_link_options(-fsanitize=address,undefined)
endif()
# Export compile commands for IDE integration
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
Debug Logging Pattern
#include <iostream>
#include <source_location>
// Modern debug logging (C++20)
template<typename... Args>
void debug_log(Args&&... args,
std::source_location loc = std::source_location::current()) {
#ifndef NDEBUG
std::cerr << "[DEBUG] " << loc.file_name() << ":"
<< loc.line() << " (" << loc.function_name() << "): ";
(std::cerr << ... << std::forward<Args>(args)) << '\n';
#endif
}
// Usage
void process(int x) {
debug_log("Processing value: ", x);
// ...
}
Unit Test Template
#include <gtest/gtest.h>
#include <signal.h>
class DebuggingTest : public ::testing::Test {
protected:
void SetUp() override {
// Enable core dumps for this test
struct rlimit core_limit;
core_limit.rlim_cur = RLIM_INFINITY;
core_limit.rlim_max = RLIM_INFINITY;
setrlimit(RLIMIT_CORE, &core_limit);
}
};
// Test that sanitizers catch issues
TEST_F(DebuggingTest, DetectsBufferOverflow) {
// This should be caught by ASan if enabled
// Only run with sanitizers in CI
#ifdef __SANITIZE_ADDRESS__
GTEST_SKIP() << "Would trigger ASan, skipping";
#endif
}
TEST_F(DebuggingTest, DebugSymbolsPresent) {
// Verify debug build
#ifdef NDEBUG
FAIL() << "Tests should run in debug mode";
#endif
}
// Death test for expected crashes
TEST_F(DebuggingTest, CrashOnNullDeref) {
EXPECT_DEATH({
int* p = nullptr;
*p = 42;
}, "");
}
Integration Points
| Component | Interface |
|---|---|
build-engineer | Debug build flags |
memory-specialist | Memory issue patterns |
performance-optimizer | Performance debugging |
modern-cpp-expert | Smart pointer debugging |
C++ Plugin v3.0.0 - Production-Grade Development Skill
Memory Management Skill
Production-Grade Learning Skill | Safe Resource Handling
Master C++ memory management for safe, efficient, and leak-free code.
Core Principles
The Golden Rule: RAII
Resource Acquisition Is Initialization
// ─────────────────────────────────────────────────────
// RAII wrapper for file handles
// ─────────────────────────────────────────────────────
class FileHandle {
FILE* handle_{nullptr};
public:
explicit FileHandle(const char* path, const char* mode)
: handle_(fopen(path, mode))
{
if (!handle_) {
throw std::runtime_error("Failed to open file");
}
}
~FileHandle() {
if (handle_) fclose(handle_);
}
// Non-copyable
FileHandle(const FileHandle&) = delete;
FileHandle& operator=(const FileHandle&) = delete;
// Movable
FileHandle(FileHandle&& other) noexcept
: handle_(std::exchange(other.handle_, nullptr)) {}
FileHandle& operator=(FileHandle&& other) noexcept {
if (this != &other) {
if (handle_) fclose(handle_);
handle_ = std::exchange(other.handle_, nullptr);
}
return *this;
}
FILE* get() const { return handle_; }
};
// Usage: automatic cleanup guaranteed
void processFile(const char* path) {
FileHandle file(path, "r"); // Acquired
// ... use file ...
} // Automatically closed, even if exception thrown
Smart Pointers
Ownership Hierarchy
┌─────────────────────────────────────────────────────────────────┐
│ std::unique_ptr │ Exclusive ownership (default choice) │
│ std::shared_ptr │ Shared ownership (reference counted) │
│ std::weak_ptr │ Non-owning observer (breaks cycles) │
└─────────────────────────────────────────────────────────────────┘
unique_ptr (Prefer This)
// Creation (ALWAYS use make_unique)
auto widget = std::make_unique<Widget>(arg1, arg2);
// Array version
auto arr = std::make_unique<int[]>(100);
// Custom deleter
auto file = std::unique_ptr<FILE, decltype(&fclose)>(
fopen("data.txt", "r"), &fclose
);
// Transfer ownership
void takeOwnership(std::unique_ptr<Widget> w);
takeOwnership(std::move(widget)); // Explicit move required
shared_ptr (Use When Truly Needed)
// Creation
auto shared = std::make_shared<Resource>(); // Single allocation!
// Copy = increment reference count
auto copy = shared; // ref_count: 2
// Custom deleter
auto custom = std::shared_ptr<Database>(
new Database(),
[](Database* db) {
db->close();
delete db;
}
);
weak_ptr (Break Cycles)
class Node {
public:
std::shared_ptr<Node> next;
std::weak_ptr<Node> prev; // Weak to prevent cycle
};
// Safe access through lock()
void useWeakPtr(std::weak_ptr<Resource> weak) {
if (auto shared = weak.lock()) { // Returns shared_ptr or nullptr
shared->doSomething();
}
}
Memory Issues & Solutions
Quick Reference
| Problem | Detection | Solution |
|---|---|---|
| Memory leak | Valgrind, ASan | Use smart pointers |
| Dangling pointer | ASan | weak_ptr, proper lifetime |
| Double free | ASan | unique_ptr ownership |
| Buffer overflow | ASan | std::vector, std::span |
| Use after free | ASan | RAII, smart pointers |
Detecting Leaks
# Valgrind (runtime)
valgrind --leak-check=full --show-leak-kinds=all ./program
# AddressSanitizer (compile-time instrumentation)
g++ -fsanitize=address -fno-omit-frame-pointer -g program.cpp
Common Patterns
// ❌ BAD: Raw pointer ownership unclear
Widget* createWidget() {
return new Widget(); // Who deletes this?
}
// ✅ GOOD: Ownership explicit
std::unique_ptr<Widget> createWidget() {
return std::make_unique<Widget>();
}
// ❌ BAD: Exception unsafe
void process() {
Resource* r = new Resource();
doSomething(); // May throw!
delete r; // Never reached if exception
}
// ✅ GOOD: Exception safe
void process() {
auto r = std::make_unique<Resource>();
doSomething(); // Even if throws, r is deleted
}
Custom Allocators
Pool Allocator
template<typename T, size_t BlockSize = 4096>
class PoolAllocator {
struct Block {
std::array<std::byte, sizeof(T)> data;
Block* next;
};
Block* freeList_{nullptr};
std::vector<std::unique_ptr<Block[]>> blocks_;
public:
T* allocate() {
if (!freeList_) {
allocateBlock();
}
Block* block = freeList_;
freeList_ = block->next;
return reinterpret_cast<T*>(&block->data);
}
void deallocate(T* ptr) {
Block* block = reinterpret_cast<Block*>(ptr);
block->next = freeList_;
freeList_ = block;
}
private:
void allocateBlock() {
constexpr size_t count = BlockSize / sizeof(Block);
auto newBlocks = std::make_unique<Block[]>(count);
for (size_t i = 0; i < count - 1; ++i) {
newBlocks[i].next = &newBlocks[i + 1];
}
newBlocks[count - 1].next = freeList_;
freeList_ = &newBlocks[0];
blocks_.push_back(std::move(newBlocks));
}
};
Troubleshooting
Decision Tree
Memory issue?
├── Leak suspected
│ ├── Run Valgrind → Shows "definitely lost"
│ ├── Check for raw `new` → Replace with make_unique
│ └── Check cyclic references → Use weak_ptr
├── Crash/Corruption
│ ├── Segfault at nullptr → Add null checks
│ ├── Double free → Ensure single owner (unique_ptr)
│ └── Use after free → Check object lifetime
└── Performance
├── Too many allocations → Use pool allocator
├── Fragmentation → Use arena allocator
└── False sharing → Align to cache line
Unit Test Template
#include <gtest/gtest.h>
#include <memory>
TEST(SmartPointerTest, UniquePtrOwnership) {
auto ptr = std::make_unique<int>(42);
EXPECT_NE(ptr, nullptr);
EXPECT_EQ(*ptr, 42);
auto ptr2 = std::move(ptr);
EXPECT_EQ(ptr, nullptr); // Ownership transferred
EXPECT_EQ(*ptr2, 42);
}
TEST(SmartPointerTest, SharedPtrRefCount) {
auto shared1 = std::make_shared<int>(100);
EXPECT_EQ(shared1.use_count(), 1);
auto shared2 = shared1;
EXPECT_EQ(shared1.use_count(), 2);
}
TEST(SmartPointerTest, WeakPtrExpired) {
std::weak_ptr<int> weak;
{
auto shared = std::make_shared<int>(42);
weak = shared;
EXPECT_FALSE(weak.expired());
}
EXPECT_TRUE(weak.expired());
}
C++ Plugin v3.0.0 - Production-Grade Learning Skill
Modern C++ Skill
Production-Grade Development Skill | C++11 through C++23
Leverage modern C++ standards for cleaner, safer, and more efficient code.
C++ Standards Timeline
┌─────────────────────────────────────────────────────────────────────────────┐
│ C++11 │ C++14 │ C++17 │ C++20 │ C++23 │ │
│ (2011) │ (2014) │ (2017) │ (2020) │ (2023) │ │
├──────────┼──────────┼──────────┼──────────┼──────────┤ │
│ auto │ generic │ if init │ concepts │ deducing │ │
│ lambda │ lambdas │ optional │ ranges │ this │ │
│ move │ constexpr│ variant │ modules │ std::print │
│ smart_ptr│ relaxed │ string_v │ coroutine│ flat_map │ │
└─────────────────────────────────────────────────────────────────────────────┘
Move Semantics
Value Categories
// lvalue: Has identity, can be addressed
int x = 10; // x is lvalue
int* p = &x; // Can take address
// rvalue: Temporary, no persistent identity
int y = x + 5; // (x + 5) is rvalue
// int* p2 = &(x + 5); // Error: cannot take address
// xvalue: eXpiring lvalue (about to be moved)
std::string s = "hello";
std::string t = std::move(s); // s is now xvalue
Move Constructor & Assignment
class Buffer {
std::unique_ptr<char[]> data_;
size_t size_;
public:
// Move constructor
Buffer(Buffer&& other) noexcept
: data_(std::move(other.data_))
, size_(std::exchange(other.size_, 0))
{}
// Move assignment
Buffer& operator=(Buffer&& other) noexcept {
if (this != &other) {
data_ = std::move(other.data_);
size_ = std::exchange(other.size_, 0);
}
return *this;
}
};
Perfect Forwarding
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
// Usage
auto ptr = make_unique<std::string>("hello"); // Forwards "hello"
std::string s = "world";
auto ptr2 = make_unique<std::string>(std::move(s)); // Forwards rvalue
Smart Pointers
unique_ptr - Exclusive Ownership
#include <memory>
// Creation
auto ptr = std::make_unique<Widget>(args...);
// Transfer ownership
auto ptr2 = std::move(ptr); // ptr is now nullptr
// Custom deleter
auto file = std::unique_ptr<FILE, decltype(&fclose)>(
fopen("file.txt", "r"), &fclose);
// Array version
auto arr = std::make_unique<int[]>(100);
shared_ptr - Shared Ownership
// Creation (always prefer make_shared)
auto ptr = std::make_shared<Widget>(args...);
// Share ownership
auto ptr2 = ptr; // ref_count = 2
// Check usage
std::cout << ptr.use_count(); // 2
// Weak reference (doesn't affect lifetime)
std::weak_ptr<Widget> weak = ptr;
if (auto locked = weak.lock()) {
// Use locked
}
Smart Pointer Decision Tree
Need pointer?
├── Single owner? → std::unique_ptr
├── Shared ownership? → std::shared_ptr
│ └── Need to break cycles? → std::weak_ptr
├── Non-owning view? → raw pointer or reference
└── Polymorphic container? → std::unique_ptr<Base>
Lambda Expressions
Lambda Evolution
// C++11: Basic lambda
auto f1 = [](int x) { return x * 2; };
// C++14: Generic lambda
auto f2 = [](auto x) { return x * 2; };
// C++17: constexpr lambda
constexpr auto f3 = [](int x) constexpr { return x * 2; };
// C++20: Template lambda
auto f4 = []<typename T>(std::vector<T>& v) { v.clear(); };
// C++20: Lambda with explicit template params
auto f5 = []<typename T>(T a, T b) { return a + b; };
// C++23: Deducing this
struct Widget {
auto getName(this auto&& self) {
return std::forward_like<decltype(self)>(self.name_);
}
};
Capture Modes
int x = 10;
std::string s = "hello";
// By value
auto f1 = [x]() { return x; };
// By reference
auto f2 = [&x]() { return x++; };
// Move capture (C++14)
auto f3 = [s = std::move(s)]() { return s; };
// Init capture with expression
auto f4 = [y = x * 2]() { return y; };
// Capture all by value
auto f5 = [=]() { return x + s.size(); };
// Capture all by reference
auto f6 = [&]() { x++; };
// Mixed
auto f7 = [=, &x]() { x++; return s; };
Concepts (C++20)
Standard Concepts
#include <concepts>
// Using standard concepts
template<std::integral T>
T gcd(T a, T b) {
while (b != 0) {
T t = b;
b = a % b;
a = t;
}
return a;
}
// Common concepts
template<std::floating_point T>
T sqrt(T x);
template<std::copyable T>
void process(T value);
template<std::invocable<int> F>
void apply(F&& func);
Custom Concepts
// Define concept
template<typename T>
concept Hashable = requires(T a) {
{ std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;
};
template<typename T>
concept Container = requires(T c) {
{ c.begin() } -> std::input_iterator;
{ c.end() } -> std::sentinel_for<decltype(c.begin())>;
{ c.size() } -> std::convertible_to<std::size_t>;
};
// Use concept
template<Container C>
void process(const C& container) {
for (const auto& item : container) {
// ...
}
}
Ranges (C++20)
Range Views
#include <ranges>
namespace rv = std::views;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Composable views
auto result = v
| rv::filter([](int x) { return x % 2 == 0; }) // 2, 4, 6, 8, 10
| rv::transform([](int x) { return x * x; }) // 4, 16, 36, 64, 100
| rv::take(3); // 4, 16, 36
// Views are lazy - no computation until iteration
for (int x : result) {
std::cout << x << ' ';
}
Range Algorithms
#include <algorithm>
#include <ranges>
std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};
// Range-based algorithms
std::ranges::sort(v);
std::ranges::reverse(v);
// With projections
struct Person { std::string name; int age; };
std::vector<Person> people;
std::ranges::sort(people, {}, &Person::age); // Sort by age
// Range factories
for (int i : std::views::iota(1, 10)) {} // 1..9
for (int i : std::views::repeat(42) | std::views::take(5)) {} // 42, 42, 42, 42, 42
Coroutines (C++20)
Generator Pattern
#include <coroutine>
#include <generator> // C++23
// C++23 std::generator
std::generator<int> fibonacci() {
int a = 0, b = 1;
while (true) {
co_yield a;
auto tmp = a;
a = b;
b = tmp + b;
}
}
// Usage
for (int x : fibonacci() | std::views::take(10)) {
std::cout << x << ' '; // 0 1 1 2 3 5 8 13 21 34
}
Async Task Pattern
// Simplified task coroutine
task<int> async_compute() {
co_await some_async_operation();
co_return 42;
}
task<void> example() {
int result = co_await async_compute();
std::cout << result;
}
Modules (C++20)
Module Declaration
// math.cppm - Module interface
export module math;
export int add(int a, int b) {
return a + b;
}
export namespace math {
double pi = 3.14159;
double area(double radius) {
return pi * radius * radius;
}
}
Module Import
// main.cpp
import math;
import <iostream>;
int main() {
std::cout << math::add(2, 3) << '\n';
std::cout << math::area(5.0) << '\n';
}
Migration Checklist
From C++11/14 to C++17
- Replace
std::bindwith lambdas - Use structured bindings:
auto [a, b] = pair; - Use if-init:
if (auto it = m.find(k); it != m.end()) - Replace
boost::optionalwithstd::optional - Use
std::string_viewfor read-only strings - Use
[[nodiscard]]for important return values
From C++17 to C++20
- Replace SFINAE with concepts
- Use ranges instead of begin/end pairs
- Consider modules for large projects
- Use
std::spanfor contiguous ranges - Use
<=>spaceship operator - Use designated initializers
Troubleshooting Decision Tree
Compilation error with modern feature?
├── "requires C++XX or later"
│ └── Update -std=c++XX flag
├── "concept not satisfied"
│ ├── Check type requirements
│ └── Add missing operations to type
├── "move from const"
│ └── Remove const or copy instead
├── "use of deleted function"
│ ├── Check if type is movable
│ └── Use std::move if needed
└── "incomplete type in unique_ptr"
└── Define destructor in .cpp file
Unit Test Template
#include <gtest/gtest.h>
#include <memory>
TEST(SmartPointerTest, UniquePtrTransfersOwnership) {
auto p1 = std::make_unique<int>(42);
auto p2 = std::move(p1);
EXPECT_EQ(p1, nullptr);
EXPECT_NE(p2, nullptr);
EXPECT_EQ(*p2, 42);
}
TEST(MoveTest, StringMoveLeavesEmpty) {
std::string s1 = "hello";
std::string s2 = std::move(s1);
EXPECT_TRUE(s1.empty());
EXPECT_EQ(s2, "hello");
}
TEST(ConceptTest, IntegralSatisfied) {
static_assert(std::integral<int>);
static_assert(std::integral<long>);
static_assert(!std::integral<double>);
}
TEST(RangesTest, FilterTransform) {
std::vector<int> v = {1, 2, 3, 4, 5};
std::vector<int> result;
for (int x : v | std::views::filter([](int x) { return x % 2 == 0; })
| std::views::transform([](int x) { return x * 2; })) {
result.push_back(x);
}
EXPECT_EQ(result, (std::vector<int>{4, 8}));
}
Integration Points
| Component | Interface |
|---|---|
memory-specialist | Smart pointer patterns |
stl-master | Modern STL features |
performance-optimizer | Move optimization |
build-engineer | C++ standard flags |
C++ Plugin v3.0.0 - Production-Grade Development Skill
OOP Patterns Skill
Production-Grade Learning Skill | Object-Oriented Design
Master C++ OOP concepts and industry-standard design patterns.
The Four Pillars
1. Encapsulation
class BankAccount {
private:
std::string id_;
double balance_{0.0}; // Default member init
public:
explicit BankAccount(std::string id) : id_(std::move(id)) {}
// Read-only access
[[nodiscard]] double balance() const { return balance_; }
[[nodiscard]] const std::string& id() const { return id_; }
// Controlled mutation with validation
void deposit(double amount) {
if (amount <= 0) {
throw std::invalid_argument("Amount must be positive");
}
balance_ += amount;
}
bool withdraw(double amount) {
if (amount <= 0 || amount > balance_) return false;
balance_ -= amount;
return true;
}
};
2. Inheritance
// Abstract base class
class Shape {
protected:
std::string name_;
public:
explicit Shape(std::string name) : name_(std::move(name)) {}
virtual ~Shape() = default; // ALWAYS virtual destructor!
// Pure virtual functions (interface)
[[nodiscard]] virtual double area() const = 0;
[[nodiscard]] virtual double perimeter() const = 0;
// Non-virtual (shared behavior)
[[nodiscard]] const std::string& name() const { return name_; }
};
class Circle final : public Shape { // final prevents further inheritance
double radius_;
public:
explicit Circle(double r) : Shape("Circle"), radius_(r) {}
[[nodiscard]] double area() const override {
return std::numbers::pi * radius_ * radius_;
}
[[nodiscard]] double perimeter() const override {
return 2 * std::numbers::pi * radius_;
}
};
3. Polymorphism
// Runtime polymorphism via virtual functions
void printShape(const Shape& shape) {
std::cout << shape.name() << ": area = " << shape.area() << "\n";
}
// Usage - same function, different behavior
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(5.0));
shapes.push_back(std::make_unique<Rectangle>(3.0, 4.0));
for (const auto& shape : shapes) {
printShape(*shape); // Polymorphic dispatch
}
4. Abstraction
// Pure interface (all pure virtual)
class ILogger {
public:
virtual ~ILogger() = default;
virtual void log(std::string_view message) = 0;
virtual void setLevel(int level) = 0;
};
// Multiple implementations
class ConsoleLogger : public ILogger {
public:
void log(std::string_view message) override {
std::cout << "[LOG] " << message << "\n";
}
void setLevel(int) override { }
};
class FileLogger : public ILogger {
std::ofstream file_;
public:
explicit FileLogger(const std::string& path) : file_(path) {}
void log(std::string_view message) override {
file_ << message << "\n";
}
void setLevel(int) override { }
};
SOLID Principles
| Principle | Summary | C++ Example |
|---|---|---|
| Single Responsibility | One class, one reason to change | Separate User from UserSerializer |
| Open/Closed | Open for extension, closed for modification | Virtual functions, inheritance |
| Liskov Substitution | Subtypes must be substitutable | Square shouldn't inherit Rectangle |
| Interface Segregation | Prefer small, specific interfaces | Split IWorker into IWorkable, IFeedable |
| Dependency Inversion | Depend on abstractions | Inject IDatabase& not MySQLDatabase |
Design Patterns
Factory Pattern
class ShapeFactory {
public:
static std::unique_ptr<Shape> create(std::string_view type, double param) {
if (type == "circle") {
return std::make_unique<Circle>(param);
}
if (type == "square") {
return std::make_unique<Square>(param);
}
throw std::invalid_argument("Unknown shape type");
}
};
// Usage
auto shape = ShapeFactory::create("circle", 5.0);
Singleton Pattern (Thread-Safe)
class Logger {
private:
Logger() = default;
public:
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
static Logger& instance() {
static Logger instance; // Thread-safe in C++11
return instance;
}
void log(std::string_view msg) { std::cout << msg << "\n"; }
};
Observer Pattern
class IObserver {
public:
virtual ~IObserver() = default;
virtual void onNotify(const std::string& event) = 0;
};
class Subject {
std::vector<IObserver*> observers_;
public:
void attach(IObserver* obs) { observers_.push_back(obs); }
void detach(IObserver* obs) {
observers_.erase(std::remove(observers_.begin(), observers_.end(), obs),
observers_.end());
}
void notify(const std::string& event) {
for (auto* obs : observers_) {
obs->onNotify(event);
}
}
};
Strategy Pattern
class ICompressionStrategy {
public:
virtual ~ICompressionStrategy() = default;
virtual std::vector<uint8_t> compress(std::span<const uint8_t> data) = 0;
};
class ZipStrategy : public ICompressionStrategy {
public:
std::vector<uint8_t> compress(std::span<const uint8_t> data) override {
// ZIP compression
return {};
}
};
class Compressor {
std::unique_ptr<ICompressionStrategy> strategy_;
public:
void setStrategy(std::unique_ptr<ICompressionStrategy> s) {
strategy_ = std::move(s);
}
std::vector<uint8_t> compress(std::span<const uint8_t> data) {
return strategy_->compress(data);
}
};
Troubleshooting
| Issue | Cause | Solution |
|---|---|---|
| Object slicing | Passing by value | Use references/pointers |
| Memory leak | Missing virtual destructor | Add virtual ~Base() = default; |
| Diamond problem | Multiple inheritance | Use virtual inheritance |
| Tight coupling | Direct dependencies | Inject interfaces |
Unit Test Template
#include <gtest/gtest.h>
TEST(ShapeTest, CircleArea) {
Circle c(5.0);
EXPECT_NEAR(c.area(), 78.5398, 0.0001);
}
TEST(ShapeTest, Polymorphism) {
std::unique_ptr<Shape> shape = std::make_unique<Circle>(1.0);
EXPECT_EQ(shape->name(), "Circle");
}
TEST(FactoryTest, CreateCircle) {
auto shape = ShapeFactory::create("circle", 5.0);
EXPECT_NE(shape, nullptr);
EXPECT_EQ(shape->name(), "Circle");
}
C++ Plugin v3.0.0 - Production-Grade Learning Skill
Performance Skill
Production-Grade Development Skill | C++ Performance Engineering
Optimize C++ code for maximum performance through profiling, analysis, and targeted optimization.
Golden Rules
┌─────────────────────────────────────────────────────────────────┐
│ 1. MEASURE first - never optimize without profiling data │
│ 2. OPTIMIZE hotspots - focus on the 20% that takes 80% time │
│ 3. VERIFY improvements - benchmark before and after │
│ 4. MAINTAIN readability - premature optimization is evil │
└─────────────────────────────────────────────────────────────────┘
Profiling Tools
Linux perf
# Record CPU profile
perf record -g ./program
perf report
# Flamegraph generation
perf script | stackcollapse-perf.pl | flamegraph.pl > flame.svg
# Hardware counters
perf stat -e cache-misses,cache-references,instructions,cycles ./program
# Specific function profiling
perf record -g -e cycles:u --call-graph dwarf ./program
Valgrind Callgrind
# Instruction-level profiling
valgrind --tool=callgrind ./program
kcachegrind callgrind.out.*
# Cache simulation
valgrind --tool=cachegrind ./program
cg_annotate cachegrind.out.*
Google Benchmark
#include <benchmark/benchmark.h>
static void BM_VectorPushBack(benchmark::State& state) {
for (auto _ : state) {
std::vector<int> v;
v.reserve(state.range(0)); // Fair comparison
for (int i = 0; i < state.range(0); ++i) {
v.push_back(i);
}
benchmark::DoNotOptimize(v.data());
benchmark::ClobberMemory();
}
state.SetComplexityN(state.range(0));
}
BENCHMARK(BM_VectorPushBack)
->Range(8, 8 << 10)
->Complexity(benchmark::oN);
BENCHMARK_MAIN();
Cache Optimization
Data Layout: AoS vs SoA
// ❌ Array of Structures (AoS) - cache unfriendly for iteration
struct ParticleAoS {
float x, y, z; // Position
float vx, vy, vz; // Velocity
float mass;
int id;
};
std::vector<ParticleAoS> particles; // 32 bytes per particle
// ✅ Structure of Arrays (SoA) - cache friendly
struct ParticlesSoA {
std::vector<float> x, y, z; // Contiguous positions
std::vector<float> vx, vy, vz; // Contiguous velocities
std::vector<float> mass;
std::vector<int> id;
void update_positions(float dt) {
const size_t n = x.size();
for (size_t i = 0; i < n; ++i) {
x[i] += vx[i] * dt; // Full cache line utilization
y[i] += vy[i] * dt;
z[i] += vz[i] * dt;
}
}
};
Cache Line Alignment
// Avoid false sharing with cache line alignment
struct alignas(64) CacheAlignedCounter {
std::atomic<long> count{0};
char padding[56]; // Ensure 64-byte alignment
};
// Per-thread counters without false sharing
std::array<CacheAlignedCounter, 8> thread_counters;
// Hot/cold data separation
struct HotData {
int frequently_accessed;
int also_frequent;
};
struct ColdData {
std::string rarely_used;
std::vector<int> debug_info;
};
struct OptimizedNode {
HotData hot;
ColdData* cold; // Pointer to cold data (loaded on demand)
};
SIMD Vectorization
Auto-vectorization Hints
// Help compiler vectorize with restrict and pragmas
void add_arrays(float* __restrict a, float* __restrict b,
float* __restrict result, size_t n) {
#pragma omp simd
for (size_t i = 0; i < n; ++i) {
result[i] = a[i] + b[i];
}
}
// Alignment for better vectorization
void process_aligned(float* data, size_t n) {
float* __restrict aligned_data =
std::assume_aligned<32>(data); // C++20
for (size_t i = 0; i < n; ++i) {
aligned_data[i] *= 2.0f;
}
}
Explicit SIMD (AVX)
#include <immintrin.h>
void add_vectors_avx(const float* a, const float* b,
float* result, size_t n) {
size_t i = 0;
// Process 8 floats at a time with AVX
for (; i + 8 <= n; i += 8) {
__m256 va = _mm256_loadu_ps(&a[i]);
__m256 vb = _mm256_loadu_ps(&b[i]);
__m256 vr = _mm256_add_ps(va, vb);
_mm256_storeu_ps(&result[i], vr);
}
// Handle remainder
for (; i < n; ++i) {
result[i] = a[i] + b[i];
}
}
// Horizontal sum with AVX
float horizontal_sum_avx(__m256 v) {
__m128 lo = _mm256_castps256_ps128(v);
__m128 hi = _mm256_extractf128_ps(v, 1);
lo = _mm_add_ps(lo, hi);
lo = _mm_hadd_ps(lo, lo);
lo = _mm_hadd_ps(lo, lo);
return _mm_cvtss_f32(lo);
}
Multithreading
Parallel Algorithms (C++17)
#include <execution>
#include <algorithm>
#include <numeric>
std::vector<int> data(1'000'000);
// Parallel sort
std::sort(std::execution::par_unseq, data.begin(), data.end());
// Parallel transform
std::transform(std::execution::par, data.begin(), data.end(),
data.begin(), [](int x) { return x * 2; });
// Parallel reduce
long sum = std::reduce(std::execution::par,
data.begin(), data.end(), 0L);
// Parallel for_each
std::for_each(std::execution::par_unseq, data.begin(), data.end(),
[](int& x) { x = process(x); });
Thread Pool
#include <thread>
#include <queue>
#include <functional>
#include <future>
#include <condition_variable>
class ThreadPool {
std::vector<std::thread> workers_;
std::queue<std::function<void()>> tasks_;
std::mutex mutex_;
std::condition_variable cv_;
std::atomic<bool> stop_{false};
public:
explicit ThreadPool(size_t threads = std::thread::hardware_concurrency()) {
for (size_t i = 0; i < threads; ++i) {
workers_.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock lock(mutex_);
cv_.wait(lock, [this] {
return stop_ || !tasks_.empty();
});
if (stop_ && tasks_.empty()) return;
task = std::move(tasks_.front());
tasks_.pop();
}
task();
}
});
}
}
template<typename F, typename... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<std::invoke_result_t<F, Args...>> {
using return_type = std::invoke_result_t<F, Args...>;
auto task = std::make_shared<std::packaged_task<return_type()>>(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<return_type> res = task->get_future();
{
std::lock_guard lock(mutex_);
tasks_.emplace([task]() { (*task)(); });
}
cv_.notify_one();
return res;
}
~ThreadPool() {
stop_ = true;
cv_.notify_all();
for (auto& worker : workers_) {
worker.join();
}
}
};
Quick Wins Checklist
Immediate Optimizations
- Use
reserve()for vectors with known size - Prefer
emplace_back()overpush_back() - Move instead of copy when possible
- Use
string_viewfor read-only strings - Avoid unnecessary allocations in loops
- Use
[[likely]]/[[unlikely]]for branch hints
Data Layout
- Profile cache misses first
- Consider SoA vs AoS for large datasets
- Align hot data to cache lines
- Separate hot and cold data
Algorithmic
- Choose right container for access pattern
- Use binary search on sorted data
- Avoid redundant computation
- Consider lookup tables for expensive functions
Performance Workflow
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ PROFILE │───▶│ IDENTIFY │───▶│ OPTIMIZE │
│ (measure) │ │ (hotspots) │ │ (implement) │
└─────────────┘ └──────────────┘ └───────────────┘
▲ │
│ ▼
│ ┌──────────────┐ ┌───────────────┐
└──────────────│ VERIFY │◀───│ BENCHMARK │
│ (improved?) │ │ (measure) │
└──────────────┘ └───────────────┘
Troubleshooting Decision Tree
Performance issue?
├── High CPU, low throughput
│ ├── Check cache misses → perf stat -e cache-misses
│ ├── Check branch mispredictions → perf stat -e branch-misses
│ └── Profile hotspots → perf record + flamegraph
├── High latency spikes
│ ├── Check for locks → Look for mutex contention
│ ├── Check allocations → Use custom allocator
│ └── Check I/O blocking → Use async I/O
├── Memory growing
│ ├── Memory leak → Valgrind / ASan
│ ├── Fragmentation → Custom allocator
│ └── Retained references → Check lifetimes
└── Inconsistent performance
├── CPU throttling → Check power management
├── NUMA effects → Pin threads to cores
└── Context switches → Reduce thread count
Unit Test Template
#include <gtest/gtest.h>
#include <benchmark/benchmark.h>
#include <chrono>
class PerformanceTest : public ::testing::Test {
protected:
static constexpr size_t ITERATIONS = 1000;
template<typename Func>
auto measure(Func&& f) {
auto start = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < ITERATIONS; ++i) {
f();
}
auto end = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::microseconds>(
end - start).count() / ITERATIONS;
}
};
TEST_F(PerformanceTest, VectorReserveIsFaster) {
auto without_reserve = measure([]{
std::vector<int> v;
for (int i = 0; i < 1000; ++i) v.push_back(i);
});
auto with_reserve = measure([]{
std::vector<int> v;
v.reserve(1000);
for (int i = 0; i < 1000; ++i) v.push_back(i);
});
EXPECT_LT(with_reserve, without_reserve);
}
TEST_F(PerformanceTest, SoAFasterThanAoS) {
// Test cache efficiency
auto aos_time = measure([this]{ process_aos(); });
auto soa_time = measure([this]{ process_soa(); });
EXPECT_LT(soa_time, aos_time * 0.8); // At least 20% faster
}
Integration Points
| Component | Interface |
|---|---|
build-engineer | Optimization flags |
modern-cpp-expert | Move semantics |
memory-specialist | Allocation patterns |
cpp-debugger-agent | Performance debugging |
C++ Plugin v3.0.0 - Production-Grade Development Skill
STL Skill
Production-Grade Learning Skill | Standard Template Library
Master C++ containers, algorithms, and iterators for efficient programming.
Container Selection Guide
Decision Flowchart
Need to store data?
│
├── Need key-value pairs?
│ ├── Need ordering? → std::map
│ └── Need fast lookup? → std::unordered_map
│
├── Need unique elements only?
│ ├── Need ordering? → std::set
│ └── Need fast lookup? → std::unordered_set
│
└── Need sequence?
├── Need random access?
│ ├── Size changes often? → std::vector (default)
│ └── Fixed size? → std::array
├── Need fast insert at both ends? → std::deque
└── Need fast insert in middle? → std::list
Complexity Reference
| Container | Access | Search | Insert | Delete |
|---|---|---|---|---|
vector | O(1) | O(n) | O(n)* | O(n) |
deque | O(1) | O(n) | O(1)** | O(1)** |
list | O(n) | O(n) | O(1) | O(1) |
set/map | - | O(log n) | O(log n) | O(log n) |
unordered_* | - | O(1)* | O(1)* | O(1)* |
*amortized **at ends
Containers
std::vector (Default Choice)
#include <vector>
std::vector<int> v;
// Initialization
std::vector<int> v1 = {1, 2, 3, 4, 5};
std::vector<int> v2(10, 0); // 10 zeros
std::vector<int> v3(v1.begin(), v1.end()); // Copy
// Modification
v.push_back(6); // Add to end
v.emplace_back(7); // Construct in place (prefer)
v.pop_back(); // Remove last
v.insert(v.begin(), 0); // Insert at position
v.erase(v.begin() + 2); // Remove at position
// Best practices
v.reserve(100); // Pre-allocate (avoid reallocations)
v.shrink_to_fit(); // Release unused memory
std::map / std::unordered_map
#include <map>
#include <unordered_map>
// Ordered map (red-black tree)
std::map<std::string, int> scores;
scores["Alice"] = 95;
scores["Bob"] = 87;
// Unordered map (hash table) - faster lookup
std::unordered_map<std::string, int> cache;
cache["key1"] = 100;
// Safe access
if (auto it = scores.find("Alice"); it != scores.end()) {
std::cout << it->second << "\n";
}
// C++17 structured bindings
for (const auto& [name, score] : scores) {
std::cout << name << ": " << score << "\n";
}
// Insert or update (C++17)
scores.insert_or_assign("Charlie", 90);
// Insert if not exists
scores.try_emplace("Dave", 85);
Algorithms
Non-Modifying
#include <algorithm>
#include <numeric>
std::vector<int> v = {1, 2, 3, 4, 5};
// Find
auto it = std::find(v.begin(), v.end(), 3);
auto it2 = std::find_if(v.begin(), v.end(), [](int n) { return n > 3; });
// Count
size_t count = std::count_if(v.begin(), v.end(), [](int n) { return n % 2 == 0; });
// All/Any/None
bool allPos = std::all_of(v.begin(), v.end(), [](int n) { return n > 0; });
bool anyNeg = std::any_of(v.begin(), v.end(), [](int n) { return n < 0; });
// Accumulate
int sum = std::accumulate(v.begin(), v.end(), 0);
int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<>());
Modifying
// Transform
std::transform(v.begin(), v.end(), v.begin(), [](int n) { return n * 2; });
// Sort
std::sort(v.begin(), v.end()); // Ascending
std::sort(v.begin(), v.end(), std::greater<>()); // Descending
// Stable sort (preserves relative order of equal elements)
std::stable_sort(v.begin(), v.end());
// Remove (erase-remove idiom)
v.erase(std::remove_if(v.begin(), v.end(), [](int n) { return n < 0; }), v.end());
// C++20: std::erase_if (much cleaner)
std::erase_if(v, [](int n) { return n < 0; });
// Unique (remove consecutive duplicates)
v.erase(std::unique(v.begin(), v.end()), v.end());
Binary Search (Sorted Containers)
std::vector<int> sorted = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Check if exists
bool found = std::binary_search(sorted.begin(), sorted.end(), 5);
// Find position
auto lower = std::lower_bound(sorted.begin(), sorted.end(), 5); // First >= 5
auto upper = std::upper_bound(sorted.begin(), sorted.end(), 5); // First > 5
auto range = std::equal_range(sorted.begin(), sorted.end(), 5); // Both
C++20 Ranges
#include <ranges>
namespace rv = std::views;
std::vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Lazy pipeline (no intermediate allocations)
auto result = data
| rv::filter([](int n) { return n % 2 == 0; }) // Keep evens
| rv::transform([](int n) { return n * n; }) // Square
| rv::take(3); // First 3
// Materialize when needed
std::vector<int> squares(result.begin(), result.end());
// squares = {4, 16, 36}
// Range algorithms
std::ranges::sort(data);
auto it = std::ranges::find(data, 5);
Troubleshooting
Iterator Invalidation
| Container | Invalidates on |
|---|---|
vector | Insert/erase (except at end) |
deque | Insert/erase (except at ends) |
list | Never (except erased element) |
map/set | Never (except erased element) |
Safe Patterns
// ❌ BAD: Iterator invalidation
for (auto it = v.begin(); it != v.end(); ++it) {
if (*it < 0) v.erase(it); // Invalidates it!
}
// ✅ GOOD: Return new iterator
for (auto it = v.begin(); it != v.end(); ) {
if (*it < 0) {
it = v.erase(it); // erase returns next valid iterator
} else {
++it;
}
}
// ✅ BETTER: Use algorithm
std::erase_if(v, [](int n) { return n < 0; });
Unit Test Template
#include <gtest/gtest.h>
TEST(STLTest, VectorOperations) {
std::vector<int> v = {1, 2, 3};
v.push_back(4);
EXPECT_EQ(v.size(), 4);
EXPECT_EQ(v.back(), 4);
v.pop_back();
EXPECT_EQ(v.size(), 3);
}
TEST(STLTest, MapOperations) {
std::map<std::string, int> m;
m["a"] = 1;
m["b"] = 2;
EXPECT_EQ(m["a"], 1);
EXPECT_TRUE(m.contains("b")); // C++20
}
TEST(STLTest, Algorithms) {
std::vector<int> v = {3, 1, 4, 1, 5, 9};
std::sort(v.begin(), v.end());
EXPECT_TRUE(std::is_sorted(v.begin(), v.end()));
auto it = std::find(v.begin(), v.end(), 5);
EXPECT_NE(it, v.end());
}
C++ Plugin v3.0.0 - Production-Grade Learning Skill
Commands 6
/cpp-debug
Development Command | Expert C++ Debugging
Professional debugging assistance with GDB, LLDB, sanitizers, and Valgrind.
Usage
/cpp-debug [issue-description] [--type=crash] [--file=path]
Arguments
| Argument | Type | Required | Description |
|---|---|---|---|
issue | string | No | Description of the problem |
--type | string | No | crash, memory, logic, performance, concurrency |
--file | string | No | Specific file to debug |
Issue Types
| Type | Symptoms | Primary Tools |
|---|---|---|
| crash | Segfault, SIGABRT | GDB, ASan |
| memory | Leaks, corruption | Valgrind, ASan |
| logic | Wrong output | GDB, logging |
| performance | Slow execution | perf, callgrind |
| concurrency | Races, deadlocks | TSan, GDB threads |
Examples
# General debugging session
/cpp-debug
# Specific issue
/cpp-debug "segfault on line 42"
/cpp-debug "memory leak in process()"
/cpp-debug "race condition" --type=concurrency
# Debug specific file
/cpp-debug --file=src/parser.cpp
# Crash debugging
/cpp-debug --type=crash "crash when input is empty"
Debugging Workflow
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ REPRODUCE │───▶│ ISOLATE │───▶│ INSTRUMENT │
│ (confirm) │ │ (minimize) │ │ (observe) │
└─────────────┘ └──────────────┘ └───────────────┘
│ │
▼ ▼
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ VERIFY │◀───│ FIX │◀───│ ANALYZE │
│ (test) │ │ (correct) │ │ (root cause) │
└─────────────┘ └──────────────┘ └───────────────┘
Tool Reference
GDB Commands
run # Start program
break main # Set breakpoint
break file.cpp:42 # Breakpoint at line
next (n) # Step over
step (s) # Step into
print var # Show variable
backtrace (bt) # Call stack
info locals # Local variables
watch var # Break on change
Sanitizer Flags
# AddressSanitizer (memory errors)
g++ -fsanitize=address -g program.cpp
# UndefinedBehaviorSanitizer
g++ -fsanitize=undefined -g program.cpp
# ThreadSanitizer (data races)
g++ -fsanitize=thread -g program.cpp
# Combined
g++ -fsanitize=address,undefined -g -O1 program.cpp
Valgrind
# Memory leak check
valgrind --leak-check=full ./program
# Detailed with origins
valgrind --leak-check=full --track-origins=yes ./program
# Cache profiling
valgrind --tool=cachegrind ./program
Common Issues
| Issue | Symptoms | Diagnosis | Fix |
|---|---|---|---|
| Null dereference | SIGSEGV at low address | Check pointer before use | Add null checks |
| Buffer overflow | Corruption, random crash | Run with ASan | Fix bounds |
| Use after free | Random crash, corruption | ASan/Valgrind | Fix lifetimes |
| Memory leak | Growing memory | Valgrind | Use RAII/smart pointers |
| Data race | Inconsistent behavior | TSan | Add synchronization |
| Deadlock | Program hangs | GDB thread info | Fix lock ordering |
| Stack overflow | SIGSEGV in deep call | Check recursion | Reduce depth |
| Integer overflow | Wrong calculation | UBSan | Use checked math |
Quick Diagnosis
# Compile with debug info
g++ -g -O0 program.cpp -o program
# Quick backtrace from crash
gdb -batch -ex "run" -ex "bt" ./program
# Memory check
valgrind --leak-check=full ./program 2>&1 | head -50
# Check for undefined behavior
g++ -fsanitize=undefined -g program.cpp && ./a.out
Debug Checklist
Before Debugging
- Can you reproduce the issue consistently?
- Is the code compiled with
-g -O0? - Do you have a minimal test case?
During Debugging
- Where exactly does it crash/fail?
- What are the variable values at that point?
- What's the call stack?
After Fix
- Does the fix address the root cause?
- Are there similar bugs elsewhere?
- Did you add a regression test?
Error Messages
| Error | Cause | Solution |
|---|---|---|
| "Cannot reproduce" | Issue is intermittent | Add logging, run multiple times |
| "GDB not found" | Debugger not installed | Install: apt install gdb |
| "No debug symbols" | Missing -g flag | Recompile with -g |
| "Heisenbug" | Bug disappears in debugger | Use logging instead |
Integration Points
| Component | Interface |
|---|---|
cpp-debugger-agent | Primary debugging agent |
memory-specialist | Memory-related issues |
performance-optimizer | Performance debugging |
build-engineer | Debug build configuration |
C++ Plugin v3.0.0 - Production-Grade Development Command
/cpp-learn
Learning Command | Interactive C++ Education
Launch an expert-guided learning session for any C++ topic.
Usage
/cpp-learn [topic] [--level=intermediate] [--style=mixed]
Arguments
| Argument | Type | Required | Description |
|---|---|---|---|
topic | string | No | Specific topic to learn |
--level | string | No | beginner, intermediate, advanced |
--style | string | No | conceptual, hands-on, visual, mixed |
Topic Routing
| Topic Keywords | Routes To | Focus |
|---|---|---|
| fundamentals, basics, syntax | cpp-fundamentals-agent | Core language |
| oop, classes, inheritance | cpp-oop-agent | Object-oriented |
| memory, pointers, RAII | memory-specialist | Memory management |
| stl, containers, iterators | stl-master | Standard library |
| algorithms, complexity | cpp-algorithms-agent | Data structures |
| modern, c++20, concepts | modern-cpp-expert | Modern features |
Examples
# General learning session (starts with fundamentals)
/cpp-learn
# Specific topic
/cpp-learn pointers
/cpp-learn "smart pointers"
/cpp-learn oop
/cpp-learn stl
# With level specification
/cpp-learn templates --level=advanced
/cpp-learn basics --level=beginner
# With learning style
/cpp-learn algorithms --style=hands-on
/cpp-learn memory --style=visual
Learning Curriculum
Beginner Track
1. Variables & Data Types
2. Control Flow (if, loops)
3. Functions & Parameters
4. Arrays & Strings
5. Introduction to Pointers
6. Basic I/O Operations
Intermediate Track
1. Classes & Objects
2. Inheritance & Polymorphism
3. Smart Pointers & RAII
4. STL Containers
5. STL Algorithms
6. Error Handling
Advanced Track
1. Templates & Metaprogramming
2. Move Semantics
3. Concepts & Constraints
4. Ranges & Views
5. Coroutines
6. Performance Optimization
Teaching Approach
1. Concept Explanation
Clear, concise explanation of the concept with real-world analogies.
2. Code Demonstration
// Example with best practices
auto widget = std::make_unique<Widget>();
widget->process();
// No manual delete needed - RAII handles cleanup
3. Common Mistakes
// ❌ DON'T: Raw new without delete
Widget* w = new Widget(); // Memory leak risk!
// ✅ DO: Use smart pointers
auto w = std::make_unique<Widget>();
4. Practice Suggestions
- Try implementing the concept yourself
- Modify the example to explore edge cases
- Use
/cpp-practicefor hands-on exercises
Skill Assessment
| Level | Characteristics |
|---|---|
| Beginner | New to C++, familiar with basic programming |
| Intermediate | Comfortable with OOP, learning STL |
| Advanced | Exploring templates, optimization, modern C++ |
Session Features
- Interactive Q&A: Ask follow-up questions anytime
- Code Examples: Working code you can compile and run
- Visualizations: Diagrams for complex concepts
- Progress Tracking: Build on previous sessions
- Practice Links: Connected to
/cpp-practicefor exercises
Error Messages
| Error | Cause | Solution |
|---|---|---|
| "Unknown topic" | Topic not recognized | Use suggested alternatives |
| "Level mismatch" | Content too advanced/basic | Adjust --level parameter |
Integration Points
| Component | Interface |
|---|---|
cpp-fundamentals-agent | Basic concepts |
cpp-oop-agent | OOP patterns |
memory-specialist | Memory management |
stl-master | STL education |
cpp-algorithms-agent | Algorithm design |
modern-cpp-expert | Modern C++ features |
C++ Plugin v3.0.0 - Production-Grade Learning Command
/cpp-new
Development Command | Create New C++ Project
Generate a production-ready C++ project with modern CMake, testing, and tooling.
Usage
/cpp-new <project-name> [template] [--std=20]
Arguments
| Argument | Type | Required | Description |
|---|---|---|---|
project-name | string | Yes | Name of the project (alphanumeric, hyphens) |
template | string | No | Project template (default: full) |
--std | integer | No | C++ standard: 17, 20, 23 (default: 20) |
Project Templates
| Template | Description | Includes |
|---|---|---|
| cli | Command-line application | argparse, logging, exit codes |
| lib | Library project | Header-only or static/shared lib |
| app | Application with GUI | Qt/SDL integration ready |
| test | Test-focused project | GTest, Catch2 setup |
| full | Complete project | All features, CI/CD ready |
| minimal | Bare minimum | Just CMake and main.cpp |
Examples
# Full-featured project with C++20
/cpp-new my-project full
# CLI tool with C++23
/cpp-new my-cli cli --std=23
# Header-only library
/cpp-new my-lib lib
# Minimal starter
/cpp-new quick-test minimal
Generated Structure
my-project/
├── CMakeLists.txt # Modern CMake 3.20+
├── CMakePresets.json # Build presets
├── src/
│ ├── main.cpp # Entry point
│ └── lib/
│ └── core.cpp # Library source
├── include/
│ └── my-project/
│ └── core.hpp # Public headers
├── tests/
│ ├── CMakeLists.txt
│ └── test_core.cpp # Unit tests
├── cmake/
│ ├── CompilerWarnings.cmake # Warning flags
│ ├── Sanitizers.cmake # ASan, UBSan config
│ └── CPM.cmake # Package manager
├── .github/
│ └── workflows/
│ └── ci.yml # GitHub Actions CI
├── .clang-format # Code formatting
├── .clang-tidy # Static analysis
├── .gitignore # Git ignore rules
├── LICENSE # MIT license
└── README.md # Project documentation
CMake Features Included
Core Configuration
cmake_minimum_required(VERSION 3.20)
project(my-project VERSION 1.0.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
Build Options
option(BUILD_TESTING "Build tests" ON)
option(ENABLE_SANITIZERS "Enable ASan/UBSan" ON)
option(ENABLE_COVERAGE "Enable code coverage" OFF)
option(ENABLE_LTO "Enable link-time optimization" OFF)
Compiler Warnings (Auto-configured)
- GCC/Clang:
-Wall -Wextra -Wpedantic -Werror - MSVC:
/W4 /WX
Quick Start After Creation
# Navigate to project
cd my-project
# Configure (Debug)
cmake --preset debug
# Build
cmake --build build/debug
# Run tests
ctest --test-dir build/debug --output-on-failure
# Configure (Release)
cmake --preset release
cmake --build build/release
Validation Rules
| Rule | Validation |
|---|---|
| Project name | Must start with letter, alphanumeric/hyphens only |
| Directory | Must not already exist (or confirm overwrite) |
| Template | Must be one of: cli, lib, app, test, full, minimal |
| C++ Standard | Must be 17, 20, or 23 |
Error Messages
| Error | Cause | Solution |
|---|---|---|
| "Invalid project name" | Name contains invalid characters | Use alphanumeric and hyphens |
| "Directory exists" | Project folder already present | Choose different name or use --force |
| "Template not found" | Unknown template name | Use one of: cli, lib, app, test, full |
| "CMake failed" | CMake configuration error | Check CMake version (need 3.20+) |
Integration Points
| Component | Interface |
|---|---|
build-engineer | CMake configuration |
modern-cpp-expert | C++ standard features |
cpp-debugger-agent | Sanitizer setup |
performance-optimizer | Release build flags |
C++ Plugin v3.0.0 - Production-Grade Development Command
/cpp-optimize
Development Command | Performance Optimization
Expert-guided performance optimization with profiling, analysis, and implementation.
Usage
/cpp-optimize [focus] [--target=throughput] [--file=path]
Arguments
| Argument | Type | Required | Description |
|---|---|---|---|
focus | string | No | profile, cache, simd, parallel, algorithm, memory |
--target | string | No | throughput, latency, memory, binary_size |
--file | string | No | Specific file to optimize |
Focus Areas
| Focus | Description | Tools Used |
|---|---|---|
| profile | Find bottlenecks | perf, VTune, callgrind |
| cache | Improve cache utilization | cachegrind, perf stat |
| simd | Vectorize computations | compiler reports, intrinsics |
| parallel | Multi-threading | OpenMP, std::execution |
| algorithm | Better data structures | Complexity analysis |
| memory | Reduce allocations | Allocator profiling |
Examples
# General optimization review
/cpp-optimize
# Find bottlenecks first
/cpp-optimize profile
# Cache optimization
/cpp-optimize cache
# Add parallelism
/cpp-optimize parallel
# Specific file
/cpp-optimize --file=src/engine.cpp
# Optimize for latency
/cpp-optimize --target=latency
Optimization Workflow
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ PROFILE │───▶│ IDENTIFY │───▶│ OPTIMIZE │
│ (measure) │ │ (hotspots) │ │ (implement) │
└─────────────┘ └──────────────┘ └───────────────┘
▲ │
│ ▼
│ ┌──────────────┐ ┌───────────────┐
└──────────────│ VERIFY │◀───│ BENCHMARK │
│ (improved?) │ │ (measure) │
└──────────────┘ └───────────────┘
Profiling Commands
Linux perf
# CPU profiling
perf record -g ./program
perf report
# Hardware counters
perf stat -e cache-misses,cache-references,cycles ./program
# Flamegraph
perf script | stackcollapse-perf.pl | flamegraph.pl > flame.svg
Valgrind Callgrind
valgrind --tool=callgrind ./program
kcachegrind callgrind.out.*
Google Benchmark
#include <benchmark/benchmark.h>
static void BM_Function(benchmark::State& state) {
for (auto _ : state) {
// Code to benchmark
benchmark::DoNotOptimize(result);
}
}
BENCHMARK(BM_Function);
Quick Wins Checklist
Immediate Optimizations
- Use
reserve()for vectors with known size - Prefer
emplace_back()overpush_back() - Move instead of copy when possible
- Use
string_viewfor read-only strings - Avoid allocations in hot loops
- Use
[[likely]]/[[unlikely]]for branch hints
Data Layout
- Consider SoA vs AoS for large datasets
- Align hot data to cache lines (64 bytes)
- Separate hot and cold data
- Reduce struct padding
Algorithmic
- Choose right container for access pattern
- Use binary search on sorted data
- Consider lookup tables for expensive functions
- Eliminate redundant computation
Optimization Techniques
Cache Optimization
// SoA for better cache utilization
struct ParticlesSoA {
std::vector<float> x, y, z; // Contiguous access
void update(float dt) {
for (size_t i = 0; i < x.size(); ++i) {
x[i] += vx[i] * dt; // Cache-friendly
}
}
};
SIMD Vectorization
// Help compiler auto-vectorize
void add(float* __restrict a, float* __restrict b,
float* __restrict c, size_t n) {
#pragma omp simd
for (size_t i = 0; i < n; ++i) {
c[i] = a[i] + b[i];
}
}
Parallelization
#include <execution>
// Parallel sort
std::sort(std::execution::par_unseq, v.begin(), v.end());
// Parallel reduce
auto sum = std::reduce(std::execution::par, v.begin(), v.end());
Compiler Flags
| Purpose | GCC/Clang | MSVC |
|---|---|---|
| Max optimization | -O3 | /O2 |
| Native CPU | -march=native | /arch:AVX2 |
| LTO | -flto | /GL /LTCG |
| No exceptions | -fno-exceptions | /EHs-c- |
| Fast math | -ffast-math | /fp:fast |
Profile-Guided Optimization
# Step 1: Instrument
g++ -fprofile-generate -O3 program.cpp -o program
# Step 2: Run with typical workload
./program typical_input.txt
# Step 3: Optimize with profile
g++ -fprofile-use -O3 program.cpp -o program_optimized
Troubleshooting
| Symptom | Likely Cause | Investigation |
|---|---|---|
| High CPU, low throughput | Cache misses | perf stat -e cache-misses |
| Variable latency | Lock contention | Check mutex wait times |
| Memory growing | Allocator pressure | Profile allocations |
| Single core maxed | No parallelism | Add std::execution |
Error Messages
| Error | Cause | Solution |
|---|---|---|
| "No bottleneck found" | Code already optimal | Focus on algorithms |
| "perf not found" | Missing profiler | apt install linux-tools-generic |
| "Regression detected" | Optimization broke something | Rollback, investigate |
| "Minimal improvement" | Amdahl's Law | Parallelize different section |
Integration Points
| Component | Interface |
|---|---|
performance-optimizer | Primary optimization agent |
build-engineer | Compiler flags |
modern-cpp-expert | Move semantics |
stl-master | Container selection |
C++ Plugin v3.0.0 - Production-Grade Development Command
/cpp-practice
Learning Command | Coding Exercises & Challenges
Practice C++ programming with exercises tailored to your skill level.
Usage
/cpp-practice [difficulty] [topic] [--count=1]
Arguments
| Argument | Type | Required | Description |
|---|---|---|---|
difficulty | string | No | easy, medium, hard, interview |
topic | string | No | Specific topic for exercise |
--count | integer | No | Number of exercises (1-5) |
Difficulty Levels
| Level | Focus | Time | Topics |
|---|---|---|---|
| Easy | Fundamentals, syntax | 15-30 min | Variables, loops, functions |
| Medium | OOP, STL usage | 30-60 min | Classes, containers, algorithms |
| Hard | Advanced patterns | 1-2 hours | Templates, optimization, design |
| Interview | Common interview Q's | Varies | LeetCode-style problems |
Examples
# Random challenge at medium difficulty
/cpp-practice
# Easy fundamentals exercise
/cpp-practice easy
# Hard algorithm problem
/cpp-practice hard algorithms
# STL-focused medium challenge
/cpp-practice medium stl
# Interview preparation
/cpp-practice interview
# Multiple exercises
/cpp-practice medium --count=3
Topic Categories
Fundamentals
- Variables and data types
- Control flow (if, switch, loops)
- Functions and parameters
- Arrays and strings
- Basic I/O
Object-Oriented Programming
- Class design
- Inheritance hierarchies
- Polymorphism and virtual functions
- Operator overloading
- SOLID principles
STL & Containers
- Vector operations
- Map and set usage
- Algorithm application
- Iterator patterns
- Custom comparators
Memory Management
- Pointer arithmetic
- Smart pointer usage
- RAII implementation
- Memory debugging
- Resource management
Algorithms
- Sorting variations
- Searching techniques
- Graph traversal
- Dynamic programming
- Greedy algorithms
Modern C++
- Lambda expressions
- Move semantics
- Templates and concepts
- Ranges and views
- Structured bindings
Exercise Format
1. Problem Statement
Clear description of what to implement.
2. Requirements
Input: Vector of integers
Output: Sum of even numbers
Constraints: n <= 10^6, -10^9 <= a[i] <= 10^9
3. Examples
Input: [1, 2, 3, 4, 5, 6]
Output: 12 // 2 + 4 + 6
4. Starter Code
#include <vector>
int sumEven(const std::vector<int>& nums) {
// Your implementation here
}
5. Test Cases
assert(sumEven({1, 2, 3, 4}) == 6);
assert(sumEven({}) == 0);
assert(sumEven({1, 3, 5}) == 0);
Learning Features
Hints System
Request hints without seeing the full solution:
- Hint 1: Algorithm approach
- Hint 2: Data structure suggestion
- Hint 3: Partial implementation
Solution Walk-through
After solving (or giving up):
- Optimal solution code
- Step-by-step explanation
- Complexity analysis
- Alternative approaches
Progress Tracking
- Exercises completed
- Success rate by topic
- Time statistics
- Skill level progression
Sample Exercises
Easy: Reverse String
// Reverse a string in-place
void reverse(std::string& s);
// Input: "hello" → Output: "olleh"
Medium: Find Duplicates
// Find all duplicate elements in O(n) time
std::vector<int> findDuplicates(std::vector<int>& nums);
// Input: [4,3,2,7,8,2,3,1] → Output: [2,3]
Hard: LRU Cache
// Implement LRU Cache with O(1) get and put
class LRUCache {
LRUCache(int capacity);
int get(int key);
void put(int key, int value);
};
Commands During Exercise
| Command | Action |
|---|---|
hint | Get next hint |
solution | See full solution |
skip | Move to next exercise |
test | Run test cases |
submit | Check your solution |
Error Messages
| Error | Cause | Solution |
|---|---|---|
| "Wrong answer" | Logic error | Review test case that failed |
| "Time limit" | O(n²) or worse | Optimize algorithm |
| "Runtime error" | Crash in code | Check bounds, nulls |
| "Compile error" | Syntax issue | Fix compilation errors |
Integration Points
| Component | Interface |
|---|---|
cpp-fundamentals-agent | Easy exercises |
cpp-oop-agent | OOP exercises |
cpp-algorithms-agent | Algorithm challenges |
stl-master | STL exercises |
C++ Plugin v3.0.0 - Production-Grade Learning Command
/cpp-review
Development Command | Professional Code Review
Comprehensive code review with detailed feedback on C++ implementations.
Usage
/cpp-review [focus] [--scope=file] [--file=path]
Arguments
| Argument | Type | Required | Description |
|---|---|---|---|
focus | string | No | full, performance, memory, thread, security, style |
--scope | string | No | file, function, class, project |
--file | string | No | Specific file to review |
Review Aspects
| Aspect | What's Checked |
|---|---|
| Correctness | Logic errors, edge cases, undefined behavior |
| Efficiency | Algorithm choice, complexity, redundant operations |
| Safety | Memory safety, null checks, bounds checking |
| Style | C++ Core Guidelines, naming, formatting |
| Readability | Clear code, good naming, documentation |
| Thread Safety | Race conditions, proper synchronization |
| Security | Input validation, buffer overflows, injection |
Examples
# Full review of current file
/cpp-review
# Performance-focused review
/cpp-review performance
# Memory safety review
/cpp-review memory
# Thread safety review
/cpp-review thread
# Review specific file
/cpp-review --file=src/parser.cpp
# Review entire class
/cpp-review --scope=class
Feedback Format
1. Summary
Grade: B+
Files Reviewed: 3
Total Issues: 7 (0 Critical, 2 Major, 5 Minor)
2. Strengths
- Good use of RAII
- Clear function naming
- Proper const-correctness
3. Issues (by Severity)
Critical Issues
// Line 42: Use after free
auto* ptr = obj.get();
obj.reset();
ptr->method(); // 🔴 CRITICAL: Use after free
Major Issues
// Line 78: Potential null dereference
void process(Widget* w) {
w->run(); // 🟠 MAJOR: No null check
}
Minor Issues
// Line 95: Prefer emplace_back
vec.push_back(Widget{}); // 🟡 MINOR: Use emplace_back
4. Suggestions
// Line 120: Consider using string_view
void log(const std::string& msg); // 🟢 Consider: string_view
Severity Levels
| Level | Symbol | Meaning | Action Required |
|---|---|---|---|
| Critical | 🔴 | Security issue, crash, UB | Must fix immediately |
| Major | 🟠 | Logic error, performance issue | Should fix |
| Minor | 🟡 | Style, readability issue | Nice to fix |
| Suggestion | 🟢 | Optional improvement | Consider for future |
Review Checklist
Correctness
- No undefined behavior
- All paths return a value
- Correct operator precedence
- No integer overflow in arithmetic
- Edge cases handled
Memory Safety
- No memory leaks
- No use after free
- No double free
- Smart pointers used appropriately
- RAII for all resources
Performance
- Appropriate algorithm complexity
- No unnecessary copies
- Containers reserved when size known
- No redundant allocations
Thread Safety
- Shared data properly synchronized
- No data races
- No deadlock potential
- Atomic operations where needed
Style & Readability
- Consistent naming convention
- Functions under 50 lines
- Clear variable names
- Appropriate comments
- No magic numbers
Modern C++
- Smart pointers over raw
- Range-based for loops
- auto where appropriate
- constexpr where possible
- noexcept where applicable
Common Issues Found
| Issue | Frequency | Severity | Fix |
|---|---|---|---|
| Missing null check | Very Common | Major | Add guard |
| Raw new/delete | Common | Major | Use smart ptr |
| Copy instead of move | Common | Minor | Add std::move |
| Unused variable | Common | Minor | Remove or use |
| Magic numbers | Common | Minor | Use named const |
| Missing const | Very Common | Minor | Add const |
| Poor naming | Common | Minor | Rename clearly |
Refactoring Examples
Before
void process(Widget* w) {
if (w != NULL) {
vector<int> v;
for (int i = 0; i < 100; i++) {
v.push_back(i);
}
w->run();
}
}
After
void process(Widget* widget) {
if (!widget) return; // Early return
std::vector<int> values;
values.reserve(100); // Reserve known size
for (int i = 0; i < 100; ++i) {
values.emplace_back(i); // emplace_back
}
widget->run();
}
Error Messages
| Error | Cause | Solution |
|---|---|---|
| "File not found" | Wrong path | Provide correct file path |
| "Parse error" | Invalid C++ syntax | Fix syntax errors first |
| "Too large" | File exceeds limit | Review in sections |
Integration Points
| Component | Interface |
|---|---|
modern-cpp-expert | General review |
performance-optimizer | Performance focus |
memory-specialist | Memory focus |
build-engineer | Build configuration |
C++ Plugin v3.0.0 - Production-Grade Development Command
Agents 9
Modern C++ Expert
Production-Grade Development Agent | C++11 → C++23
Expert in leveraging modern C++ features for cleaner, safer, and more performant code.
Responsibility Matrix (RACI)
| Task | Role |
|---|---|
| Modern C++ feature implementation | Responsible |
| Code migration (legacy → modern) | Responsible |
| Performance optimization | Accountable |
| Build system integration | Consulted |
| Debugging runtime issues | Informed |
Core Competencies
1. Move Semantics & Value Categories
// Rvalue references and std::move
class Buffer {
std::unique_ptr<char[]> data_;
size_t size_;
public:
// Move constructor - O(1)
Buffer(Buffer&& other) noexcept
: data_(std::move(other.data_))
, size_(std::exchange(other.size_, 0)) {}
// Move assignment
Buffer& operator=(Buffer&& other) noexcept {
if (this != &other) {
data_ = std::move(other.data_);
size_ = std::exchange(other.size_, 0);
}
return *this;
}
};
// Perfect forwarding
template<typename T, typename... Args>
std::unique_ptr<T> make_unique_wrapper(Args&&... args) {
return std::make_unique<T>(std::forward<Args>(args)...);
}
2. Smart Pointers
// Exclusive ownership
auto widget = std::make_unique<Widget>();
// Shared ownership with custom deleter
auto file = std::shared_ptr<FILE>(
fopen("data.txt", "r"),
[](FILE* f) { if (f) fclose(f); }
);
// Weak reference for cache
class Cache {
std::unordered_map<int, std::weak_ptr<Resource>> cache_;
public:
std::shared_ptr<Resource> get(int id) {
if (auto it = cache_.find(id); it != cache_.end()) {
if (auto sp = it->second.lock()) return sp;
}
auto resource = std::make_shared<Resource>(id);
cache_[id] = resource;
return resource;
}
};
3. Concepts & Constraints (C++20)
// Custom concept
template<typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;
template<typename T>
concept Hashable = requires(T t) {
{ std::hash<T>{}(t) } -> std::convertible_to<std::size_t>;
};
// Constrained function
template<Numeric T>
T safe_divide(T a, T b) {
if constexpr (std::floating_point<T>) {
return b != 0 ? a / b : std::numeric_limits<T>::quiet_NaN();
} else {
return b != 0 ? a / b : 0;
}
}
4. Ranges & Views (C++20)
#include <ranges>
namespace rv = std::views;
std::vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Lazy pipeline - no intermediate allocations
auto result = data
| rv::filter([](int n) { return n % 2 == 0; })
| rv::transform([](int n) { return n * n; })
| rv::take(3);
// Materialize when needed
std::vector<int> squares(result.begin(), result.end()); // {4, 16, 36}
5. Coroutines (C++20)
#include <coroutine>
template<typename T>
struct Generator {
struct promise_type {
T current_value;
auto get_return_object() {
return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};
}
auto initial_suspend() { return std::suspend_always{}; }
auto final_suspend() noexcept { return std::suspend_always{}; }
auto yield_value(T value) {
current_value = std::move(value);
return std::suspend_always{};
}
void return_void() {}
void unhandled_exception() { std::terminate(); }
};
std::coroutine_handle<promise_type> handle_;
// ... iterator interface
};
Generator<int> fibonacci(int limit) {
int a = 0, b = 1;
while (a < limit) {
co_yield a;
auto next = a + b;
a = b;
b = next;
}
}
Workflow
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ INPUT │───▶│ ANALYZE │───▶│ IMPLEMENT │
│ (request) │ │ (context) │ │ (code) │
└─────────────┘ └──────────────┘ └───────────────┘
│ │
▼ ▼
┌──────────────┐ ┌───────────────┐
│ VALIDATE │◀───│ REVIEW │
│ (compile) │ │ (quality) │
└──────────────┘ └───────────────┘
│
▼
┌──────────────┐
│ DELIVER │
│ (solution) │
└──────────────┘
Error Handling
Failure Modes & Recovery
| Failure Mode | Detection | Recovery Action |
|---|---|---|
| Compilation error | Compiler output | Parse error, suggest fix |
| Undefined behavior | Sanitizer output | Add runtime checks |
| Performance regression | Benchmark | Profile and optimize |
| API compatibility break | Version check | Provide migration path |
Retry Logic
Attempt 1: Execute → Fail
↓ wait 1s (+ jitter)
Attempt 2: Execute → Fail
↓ wait 2s (+ jitter)
Attempt 3: Execute → Fail
↓ wait 4s (+ jitter)
Fallback: Alternative approach or escalate
Troubleshooting
Decision Tree
Problem detected?
├── Compilation error
│ ├── Missing header → Check includes
│ ├── Type mismatch → Check template args
│ └── Concept not satisfied → Check constraints
├── Runtime error
│ ├── Segfault → Check ownership/lifetime
│ ├── Memory leak → Use smart pointers
│ └── Data race → Add synchronization
└── Performance issue
├── Slow compile → Reduce template depth
├── Large binary → Use extern templates
└── Slow runtime → Profile first
Debug Checklist
- Compiler version supports target C++ standard
- All includes present and correct
- Smart pointer ownership is clear
- Move operations are noexcept where possible
- Concepts constraints are satisfiable
- No dangling references to temporaries
Integration Points
| Component | Interface |
|---|---|
build-engineer | CMake standard flags |
performance-optimizer | Profiling feedback |
memory-specialist | Ownership analysis |
cpp-debugger-agent | Runtime diagnostics |
Standards Reference
| Standard | Key Features |
|---|---|
| C++11 | Move semantics, lambdas, auto, smart pointers |
| C++14 | Generic lambdas, variable templates, [[deprecated]] |
| C++17 | if constexpr, structured bindings, std::optional |
| C++20 | Concepts, ranges, coroutines, modules, <=> |
| C++23 | std::expected, deducing this, std::print |
C++ Plugin v3.0.0 - Production-Grade Development Agent
Memory Specialist
Production-Grade Learning Agent | Safe C++ Memory Management
Expert in ensuring memory safety, preventing leaks, and optimizing resource handling.
Responsibility Matrix (RACI)
| Task | Role |
|---|---|
| Memory leak detection & fixing | Responsible |
| RAII pattern implementation | Responsible |
| Smart pointer guidance | Responsible |
| Custom allocator design | Accountable |
| Performance memory optimization | Consulted |
Core Competencies
1. RAII Patterns
// Automatic resource management
class FileHandle {
FILE* handle_;
public:
explicit FileHandle(const char* path, const char* mode)
: handle_(fopen(path, mode)) {
if (!handle_) throw std::runtime_error("Failed to open file");
}
~FileHandle() {
if (handle_) fclose(handle_);
}
// Non-copyable
FileHandle(const FileHandle&) = delete;
FileHandle& operator=(const FileHandle&) = delete;
// Movable
FileHandle(FileHandle&& other) noexcept
: handle_(std::exchange(other.handle_, nullptr)) {}
FILE* get() const { return handle_; }
};
2. Smart Pointer Patterns
// Exclusive ownership - prefer this
auto widget = std::make_unique<Widget>();
// Shared ownership - use when truly needed
auto shared = std::make_shared<Resource>();
// Weak reference - break cycles, caches
class Observer {
std::weak_ptr<Subject> subject_;
public:
void update() {
if (auto sp = subject_.lock()) {
sp->notify();
}
}
};
// Custom deleter for C resources
auto file = std::unique_ptr<FILE, decltype(&fclose)>(
fopen("data.txt", "r"), &fclose
);
3. Custom Allocators
// Pool allocator for fixed-size objects
template<typename T, size_t PoolSize = 1024>
class PoolAllocator {
alignas(T) std::byte pool_[sizeof(T) * PoolSize];
std::vector<T*> free_list_;
public:
PoolAllocator() {
for (size_t i = 0; i < PoolSize; ++i) {
free_list_.push_back(reinterpret_cast<T*>(&pool_[i * sizeof(T)]));
}
}
T* allocate() {
if (free_list_.empty()) return nullptr;
T* ptr = free_list_.back();
free_list_.pop_back();
return ptr;
}
void deallocate(T* ptr) {
free_list_.push_back(ptr);
}
};
4. Memory Debugging Tools
# AddressSanitizer - compile-time instrumentation
g++ -fsanitize=address -fno-omit-frame-pointer -g program.cpp
# Valgrind - runtime detection
valgrind --leak-check=full --show-leak-kinds=all ./program
# Static analysis
clang-tidy --checks='*' program.cpp
Workflow
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ DETECT │───▶│ DIAGNOSE │───▶│ FIX │
│ (issue) │ │ (root cause)│ │ (solution) │
└─────────────┘ └──────────────┘ └───────────────┘
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ VERIFY │◀───│ PREVENT │◀───│ TEST │
│ (no regress)│ │ (patterns) │ │ (sanitizers) │
└─────────────┘ └──────────────┘ └───────────────┘
Error Handling
Common Issues & Recovery
| Issue | Detection | Recovery |
|---|---|---|
| Memory leak | Valgrind/ASan | Wrap in RAII |
| Dangling pointer | ASan, crash | Use weak_ptr |
| Buffer overflow | ASan | Use std::span |
| Double free | ASan | Unique ownership |
| Use after free | ASan | Fix lifetime |
Retry Strategy
Attempt 1: Analyze with ASan → Fail
↓ wait 1s
Attempt 2: Try Valgrind → Fail
↓ wait 2s
Attempt 3: Manual analysis → Success/Escalate
Troubleshooting
Decision Tree
Memory issue detected?
├── Leak suspected
│ ├── Run Valgrind → Check "definitely lost"
│ ├── Add ASan → Recompile and run
│ └── Review ownership → Who should delete?
├── Crash/Corruption
│ ├── Segfault → Check null, bounds
│ ├── SIGABRT → Check double-free
│ └── Random crash → Check use-after-free
└── Performance
├── Too many allocations → Use pool
├── Fragmentation → Use arena
└── Cache misses → Optimize layout
Debug Checklist
- Compiled with -g and no optimization (-O0)
- ASan/MSan enabled for debug builds
- All raw pointers have clear ownership
- Smart pointers used for heap objects
- RAII wrappers for C resources
- No manual new/delete in application code
Integration Points
| Component | Interface |
|---|---|
modern-cpp-expert | Smart pointer patterns |
cpp-debugger-agent | Runtime diagnosis |
performance-optimizer | Allocation optimization |
build-engineer | Sanitizer flags |
Quick Reference
| Problem | Solution |
|---|---|
new T | std::make_unique<T>() |
new T[n] | std::vector<T>(n) |
| Raw pointer member | std::unique_ptr<T> |
| Shared resource | std::shared_ptr<T> |
| Observer pattern | std::weak_ptr<T> |
| C resource (FILE*) | Custom RAII wrapper |
C++ Plugin v3.0.0 - Production-Grade Learning Agent
STL Master
Production-Grade Learning Agent | C++ Standard Template Library
Master of containers, algorithms, iterators, and utilities for optimal C++ solutions.
Responsibility Matrix (RACI)
| Task | Role |
|---|---|
| Container selection guidance | Responsible |
| Algorithm implementation | Responsible |
| Iterator pattern education | Responsible |
| Performance optimization | Accountable |
| Memory efficiency | Consulted |
Container Selection Guide
Sequence Containers
| Container | Access | Insert/Delete | Memory | Use Case |
|---|---|---|---|---|
vector | O(1) | O(n) / O(1) end | Contiguous | Default choice |
deque | O(1) | O(1) ends | Chunked | Double-ended queue |
list | O(n) | O(1) anywhere | Scattered | Frequent mid-insert |
forward_list | O(n) | O(1) after pos | Minimal | Singly-linked |
array | O(1) | N/A | Stack | Fixed size |
Associative Containers
| Container | Lookup | Insert | Memory | Use Case |
|---|---|---|---|---|
map | O(log n) | O(log n) | Tree | Sorted key-value |
set | O(log n) | O(log n) | Tree | Unique sorted |
multimap | O(log n) | O(log n) | Tree | Duplicate keys |
multiset | O(log n) | O(log n) | Tree | Duplicate values |
Unordered Containers
| Container | Lookup | Insert | Memory | Use Case |
|---|---|---|---|---|
unordered_map | O(1) avg | O(1) avg | Hash | Fast key-value |
unordered_set | O(1) avg | O(1) avg | Hash | Fast lookup |
Decision Flowchart
Need key-value pairs?
├── Yes → Need ordering?
│ ├── Yes → std::map
│ └── No → std::unordered_map
└── No → Need ordering?
├── Yes → Need unique?
│ ├── Yes → std::set
│ └── No → std::multiset
└── No → Need fast random access?
├── Yes → std::vector
└── No → Need fast insert anywhere?
├── Yes → std::list
└── No → std::deque
Algorithm Categories
Non-Modifying Algorithms
#include <algorithm>
#include <numeric>
std::vector<int> v = {1, 2, 3, 4, 5};
// Finding
auto it = std::find(v.begin(), v.end(), 3);
bool found = std::binary_search(v.begin(), v.end(), 3); // sorted only
// Counting
size_t count = std::count_if(v.begin(), v.end(),
[](int n) { return n % 2 == 0; });
// Checking
bool all_positive = std::all_of(v.begin(), v.end(),
[](int n) { return n > 0; });
Modifying Algorithms
// Transforming
std::transform(v.begin(), v.end(), v.begin(),
[](int n) { return n * 2; });
// Removing (erase-remove idiom)
v.erase(
std::remove_if(v.begin(), v.end(), [](int n) { return n < 0; }),
v.end()
);
// C++20: std::erase_if
std::erase_if(v, [](int n) { return n < 0; });
Sorting Algorithms
// Standard sort - O(n log n) average
std::sort(v.begin(), v.end());
// Stable sort - preserves relative order
std::stable_sort(v.begin(), v.end());
// Partial sort - only first k
std::partial_sort(v.begin(), v.begin() + 3, v.end());
// Nth element - partition around nth
std::nth_element(v.begin(), v.begin() + k, v.end());
Numeric Algorithms
#include <numeric>
int sum = std::accumulate(v.begin(), v.end(), 0);
int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<>());
// Parallel reduction (C++17)
#include <execution>
int parallel_sum = std::reduce(std::execution::par, v.begin(), v.end());
Modern STL (C++17/20/23)
C++17 Additions
// std::optional - nullable value
std::optional<int> find_value(const std::vector<int>& v, int target) {
auto it = std::find(v.begin(), v.end(), target);
if (it != v.end()) return *it;
return std::nullopt;
}
// std::variant - type-safe union
std::variant<int, std::string, double> value = "hello";
// std::filesystem
namespace fs = std::filesystem;
for (const auto& entry : fs::directory_iterator(".")) {
std::cout << entry.path() << '\n';
}
C++20 Additions
// Ranges
#include <ranges>
namespace rv = std::views;
auto result = v | rv::filter([](int n) { return n > 0; })
| rv::transform([](int n) { return n * 2; })
| rv::take(5);
// std::span - non-owning view
void process(std::span<int> data) {
for (int& x : data) x *= 2;
}
Workflow
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ ANALYZE │───▶│ SELECT │───▶│ IMPLEMENT │
│ (use case) │ │ (container) │ │ (algorithm) │
└─────────────┘ └──────────────┘ └───────────────┘
│ │
▼ ▼
┌──────────────┐ ┌───────────────┐
│ VERIFY │◀───│ OPTIMIZE │
│ (complexity) │ │ (performance) │
└──────────────┘ └───────────────┘
Troubleshooting
Common Issues
| Issue | Cause | Solution |
|---|---|---|
| Iterator invalidation | Modifying during iteration | Use indices or copy |
| Wrong container | Poor performance | Re-evaluate requirements |
| O(n²) algorithm | Nested loops | Use better algorithm |
Missing #include | Algorithm not found | Check header |
Debug Checklist
- Correct container for access pattern
- Correct algorithm for operation
- Iterator validity after modifications
- Proper range checking
- Using
std::executionpolicies correctly
Integration Points
| Component | Interface |
|---|---|
cpp-algorithms-agent | Complexity analysis |
modern-cpp-expert | Ranges, concepts |
performance-optimizer | Cache optimization |
memory-specialist | Allocation patterns |
C++ Plugin v3.0.0 - Production-Grade Learning Agent
Build Engineer
Production-Grade Development Agent | C++ Build Infrastructure
Expert in creating, configuring, and optimizing C++ build systems.
Responsibility Matrix (RACI)
| Task | Role |
|---|---|
| CMake configuration | Responsible |
| Build system setup | Responsible |
| Dependency management | Responsible |
| CI/CD pipeline creation | Accountable |
| Cross-platform builds | Responsible |
Modern CMake Patterns
Project Structure
cmake_minimum_required(VERSION 3.20)
project(MyProject
VERSION 1.0.0
LANGUAGES CXX
DESCRIPTION "A modern C++ project"
)
# ────────────────────────────────────────────────────────────────
# Global Settings
# ────────────────────────────────────────────────────────────────
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# ────────────────────────────────────────────────────────────────
# Options
# ────────────────────────────────────────────────────────────────
option(BUILD_TESTING "Build tests" ON)
option(BUILD_DOCS "Build documentation" OFF)
option(ENABLE_SANITIZERS "Enable sanitizers in debug" ON)
# ────────────────────────────────────────────────────────────────
# Compiler Warnings
# ────────────────────────────────────────────────────────────────
add_library(project_warnings INTERFACE)
target_compile_options(project_warnings INTERFACE
$<$<CXX_COMPILER_ID:GNU,Clang>:
-Wall -Wextra -Wpedantic -Werror
-Wshadow -Wnon-virtual-dtor -Wcast-align
>
$<$<CXX_COMPILER_ID:MSVC>:/W4 /WX>
)
# ────────────────────────────────────────────────────────────────
# Sanitizers (Debug only)
# ────────────────────────────────────────────────────────────────
add_library(project_sanitizers INTERFACE)
if(ENABLE_SANITIZERS AND CMAKE_BUILD_TYPE STREQUAL "Debug")
target_compile_options(project_sanitizers INTERFACE
-fsanitize=address,undefined -fno-omit-frame-pointer
)
target_link_options(project_sanitizers INTERFACE
-fsanitize=address,undefined
)
endif()
# ────────────────────────────────────────────────────────────────
# Library
# ────────────────────────────────────────────────────────────────
add_library(mylib
src/core.cpp
src/utils.cpp
)
target_include_directories(mylib PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
target_link_libraries(mylib PRIVATE project_warnings project_sanitizers)
# ────────────────────────────────────────────────────────────────
# Executable
# ────────────────────────────────────────────────────────────────
add_executable(myapp src/main.cpp)
target_link_libraries(myapp PRIVATE mylib project_warnings)
# ────────────────────────────────────────────────────────────────
# Testing
# ────────────────────────────────────────────────────────────────
if(BUILD_TESTING)
enable_testing()
add_subdirectory(tests)
endif()
Dependency Management
# Option 1: FetchContent (recommended for small deps)
include(FetchContent)
FetchContent_Declare(
fmt
GIT_REPOSITORY https://github.com/fmtlib/fmt.git
GIT_TAG 10.2.1
)
FetchContent_MakeAvailable(fmt)
target_link_libraries(mylib PRIVATE fmt::fmt)
# Option 2: find_package (for system/vcpkg/conan deps)
find_package(Boost 1.80 REQUIRED COMPONENTS filesystem)
target_link_libraries(mylib PRIVATE Boost::filesystem)
Package Managers
Conan 2.x
# conanfile.py
from conan import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake
class MyProjectConan(ConanFile):
name = "myproject"
version = "1.0.0"
settings = "os", "compiler", "build_type", "arch"
requires = ["fmt/10.2.1", "spdlog/1.13.0"]
generators = "CMakeDeps"
def generate(self):
tc = CMakeToolchain(self)
tc.generate()
def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()
# Install and build
conan install . --build=missing -of=build
cmake -B build -DCMAKE_TOOLCHAIN_FILE=build/conan_toolchain.cmake
cmake --build build
vcpkg
// vcpkg.json
{
"name": "myproject",
"version": "1.0.0",
"dependencies": [
"fmt",
"spdlog",
{ "name": "boost-filesystem", "platform": "!windows" }
]
}
# Build with vcpkg
cmake -B build -DCMAKE_TOOLCHAIN_FILE=$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake
cmake --build build
CI/CD Configuration
GitHub Actions
# .github/workflows/build.yml
name: Build
on: [push, pull_request]
jobs:
build:
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
build_type: [Debug, Release]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Install dependencies (Ubuntu)
if: matrix.os == 'ubuntu-latest'
run: sudo apt-get install -y ninja-build
- name: Configure
run: |
cmake -B build \
-G Ninja \
-DCMAKE_BUILD_TYPE=${{ matrix.build_type }} \
-DBUILD_TESTING=ON
- name: Build
run: cmake --build build
- name: Test
run: ctest --test-dir build --output-on-failure
Compiler Flags Reference
| Purpose | GCC/Clang | MSVC |
|---|---|---|
| Optimize (Release) | -O2, -O3 | /O2 |
| Debug | -g, -O0 | /Zi, /Od |
| Warnings | -Wall -Wextra | /W4 |
| Warnings as errors | -Werror | /WX |
| Sanitizers | -fsanitize=address | /fsanitize=address |
| LTO | -flto | /GL, /LTCG |
| Native arch | -march=native | /arch:AVX2 |
Workflow
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ CONFIGURE │───▶│ BUILD │───▶│ TEST │
│ (cmake) │ │ (ninja) │ │ (ctest) │
└─────────────┘ └──────────────┘ └───────────────┘
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ INSTALL │◀───│ PACKAGE │◀───│ DEPLOY │
│ (targets) │ │ (cpack) │ │ (ci/cd) │
└─────────────┘ └──────────────┘ └───────────────┘
Troubleshooting
Common Build Errors
| Error | Cause | Solution |
|---|---|---|
undefined reference | Missing library link | Add target_link_libraries |
file not found | Wrong include path | Check target_include_directories |
ABI incompatibility | Mismatched stdlib | Use same compiler everywhere |
CMake version too low | Old CMake | Upgrade or lower requirement |
Debug Checklist
-
CMAKE_EXPORT_COMPILE_COMMANDS=ONfor IDE support - Build type correctly set (
Debug/Release) - All dependencies found (
find_packagesuccess) - Compiler supports C++ standard
- Toolchain file loaded (cross-compile)
Integration Points
| Component | Interface |
|---|---|
modern-cpp-expert | C++ standard flags |
cpp-debugger-agent | Debug build config |
performance-optimizer | Release optimization |
memory-specialist | Sanitizer flags |
C++ Plugin v3.0.0 - Production-Grade Development Agent
Performance Optimizer
Production-Grade Development Agent | C++ Performance Engineering
Expert in making C++ code run faster through profiling, analysis, and targeted optimization.
Responsibility Matrix (RACI)
| Task | Role |
|---|---|
| Performance profiling | Responsible |
| Bottleneck identification | Responsible |
| Optimization implementation | Responsible |
| Benchmark creation | Accountable |
| Cache optimization | Responsible |
Golden Rules
┌─────────────────────────────────────────────────────────────────┐
│ 1. MEASURE first - never optimize without profiling data │
│ 2. OPTIMIZE hotspots - focus on the 20% that takes 80% time │
│ 3. VERIFY improvements - benchmark before and after │
│ 4. MAINTAIN readability - premature optimization is evil │
└─────────────────────────────────────────────────────────────────┘
Profiling Tools
Linux perf
# CPU profiling
perf record -g ./program
perf report
# Flamegraph generation
perf script | stackcollapse-perf.pl | flamegraph.pl > flame.svg
# Hardware counters
perf stat -e cache-misses,cache-references,instructions,cycles ./program
Valgrind Callgrind
# Instruction-level profiling
valgrind --tool=callgrind ./program
kcachegrind callgrind.out.*
# Cache simulation
valgrind --tool=cachegrind ./program
Quick Benchmarking
#include <benchmark/benchmark.h>
static void BM_VectorPushBack(benchmark::State& state) {
for (auto _ : state) {
std::vector<int> v;
for (int i = 0; i < state.range(0); ++i) {
v.push_back(i);
}
benchmark::DoNotOptimize(v.data());
}
}
BENCHMARK(BM_VectorPushBack)->Range(8, 8<<10);
BENCHMARK_MAIN();
Cache Optimization
Data Layout
// ❌ BAD: Array of Structures (AoS) - cache unfriendly for iteration
struct ParticleAoS {
float x, y, z; // Position
float vx, vy, vz; // Velocity
float mass;
int id;
};
std::vector<ParticleAoS> particles; // 32 bytes per particle
// ✅ GOOD: Structure of Arrays (SoA) - cache friendly
struct ParticlesSoA {
std::vector<float> x, y, z; // Contiguous positions
std::vector<float> vx, vy, vz; // Contiguous velocities
std::vector<float> mass;
std::vector<int> id;
void update_positions(float dt) {
// Each loop touches contiguous memory
for (size_t i = 0; i < x.size(); ++i) {
x[i] += vx[i] * dt; // Full cache line utilization
y[i] += vy[i] * dt;
z[i] += vz[i] * dt;
}
}
};
Cache Line Alignment
// Align to cache line (typically 64 bytes)
struct alignas(64) CacheAlignedData {
std::atomic<int> counter;
char padding[60]; // Prevent false sharing
};
// Per-thread data without false sharing
struct alignas(64) ThreadLocalCounter {
std::atomic<long> count{0};
char padding[56];
};
std::array<ThreadLocalCounter, 8> thread_counters;
SIMD Vectorization
Auto-vectorization Hints
// Help compiler vectorize
void add_arrays(float* __restrict a, float* __restrict b,
float* __restrict result, size_t n) {
#pragma omp simd
for (size_t i = 0; i < n; ++i) {
result[i] = a[i] + b[i];
}
}
Explicit SIMD (AVX)
#include <immintrin.h>
void add_vectors_avx(const float* a, const float* b,
float* result, size_t n) {
size_t i = 0;
// Process 8 floats at a time with AVX
for (; i + 8 <= n; i += 8) {
__m256 va = _mm256_loadu_ps(&a[i]);
__m256 vb = _mm256_loadu_ps(&b[i]);
__m256 vr = _mm256_add_ps(va, vb);
_mm256_storeu_ps(&result[i], vr);
}
// Handle remainder
for (; i < n; ++i) {
result[i] = a[i] + b[i];
}
}
Multithreading
Parallel Algorithms (C++17)
#include <execution>
#include <algorithm>
#include <numeric>
std::vector<int> data(1'000'000);
// Parallel sort
std::sort(std::execution::par_unseq, data.begin(), data.end());
// Parallel transform
std::transform(std::execution::par, data.begin(), data.end(),
data.begin(), [](int x) { return x * 2; });
// Parallel reduce
long sum = std::reduce(std::execution::par, data.begin(), data.end(), 0L);
Thread Pool Pattern
#include <thread>
#include <queue>
#include <functional>
#include <condition_variable>
class ThreadPool {
std::vector<std::thread> workers_;
std::queue<std::function<void()>> tasks_;
std::mutex mutex_;
std::condition_variable cv_;
bool stop_ = false;
public:
explicit ThreadPool(size_t threads) {
for (size_t i = 0; i < threads; ++i) {
workers_.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock lock(mutex_);
cv_.wait(lock, [this] {
return stop_ || !tasks_.empty();
});
if (stop_ && tasks_.empty()) return;
task = std::move(tasks_.front());
tasks_.pop();
}
task();
}
});
}
}
template<typename F>
void enqueue(F&& f) {
{
std::lock_guard lock(mutex_);
tasks_.emplace(std::forward<F>(f));
}
cv_.notify_one();
}
~ThreadPool() {
{ std::lock_guard lock(mutex_); stop_ = true; }
cv_.notify_all();
for (auto& w : workers_) w.join();
}
};
Workflow
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ PROFILE │───▶│ IDENTIFY │───▶│ OPTIMIZE │
│ (measure) │ │ (hotspots) │ │ (implement) │
└─────────────┘ └──────────────┘ └───────────────┘
▲ │
│ ▼
│ ┌──────────────┐ ┌───────────────┐
└──────────────│ VERIFY │◀───│ BENCHMARK │
│ (improved?) │ │ (measure) │
└──────────────┘ └───────────────┘
Optimization Checklist
Quick Wins
- Use
reserve()for vectors - Prefer
emplace_back()overpush_back() - Move instead of copy
- Avoid unnecessary string allocations
- Use
string_viewfor read-only strings
Data Layout
- SoA vs AoS analysis
- Cache line alignment
- Minimize padding/fragmentation
- Hot/cold data separation
Algorithmic
- Right container for access pattern
- Right algorithm complexity
- Early exit when possible
- Avoid redundant computation
Low-Level
- SIMD where applicable
- Branch prediction hints
- Prefetching for known access patterns
- Lock-free data structures
Troubleshooting
| Symptom | Likely Cause | Investigation |
|---|---|---|
| High CPU, low throughput | Cache misses | perf stat -e cache-misses |
| Variable latency | Lock contention | Check mutex wait times |
| Memory growing | Allocator pressure | Profile allocations |
| Single core maxed | No parallelism | Check thread usage |
Integration Points
| Component | Interface |
|---|---|
build-engineer | Optimization flags |
modern-cpp-expert | Move semantics |
memory-specialist | Allocation patterns |
cpp-debugger-agent | Performance debugging |
C++ Plugin v3.0.0 - Production-Grade Development Agent
C++ Algorithms Expert
Production-Grade Learning Agent | Algorithms & Data Structures
Expert in algorithm design, complexity analysis, and efficient C++ implementations.
Responsibility Matrix (RACI)
| Task | Role |
|---|---|
| Complexity analysis | Responsible |
| Algorithm implementation | Responsible |
| Data structure selection | Responsible |
| Optimization guidance | Accountable |
| Problem solving | Responsible |
Complexity Analysis
Big O Notation
┌─────────────────────────────────────────────────────────────────┐
│ O(1) │ Constant │ Array access, hash table lookup │
│ O(log n) │ Logarithmic │ Binary search │
│ O(n) │ Linear │ Linear search, single loop │
│ O(n log n) │ Linearithmic │ Efficient sorting (merge, quick) │
│ O(n²) │ Quadratic │ Nested loops, bubble sort │
│ O(n³) │ Cubic │ Triple nested loops │
│ O(2^n) │ Exponential │ Recursive subsets │
│ O(n!) │ Factorial │ Permutations │
└─────────────────────────────────────────────────────────────────┘
Complexity by Input Size
| n size | O(n) | O(n log n) | O(n²) | O(2^n) |
|---|---|---|---|---|
| 10 | 10 | ~33 | 100 | 1,024 |
| 100 | 100 | ~664 | 10,000 | 10^30 |
| 1,000 | 1,000 | ~10,000 | 1,000,000 | ∞ |
| 10^6 | 10^6 | ~20×10^6 | 10^12 | ∞ |
Time Limit Guide
| Time Limit | Approx. Operations | Algorithm Hint |
|---|---|---|
| 1 second | 10^8 | O(n log n) for n ≤ 10^6 |
| 2 seconds | 2×10^8 | O(n) for n ≤ 10^7 |
| 5 seconds | 5×10^8 | O(n²) for n ≤ 10^4 |
Sorting Algorithms
Quick Sort
#include <algorithm>
#include <vector>
// Using STL (preferred)
std::vector<int> v = {5, 2, 8, 1, 9};
std::sort(v.begin(), v.end()); // O(n log n) average
// Custom quicksort
void quickSort(std::vector<int>& arr, int low, int high) {
if (low >= high) return;
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; ++j) {
if (arr[j] < pivot) {
std::swap(arr[++i], arr[j]);
}
}
std::swap(arr[i + 1], arr[high]);
int partitionIndex = i + 1;
quickSort(arr, low, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, high);
}
Merge Sort (Stable)
void merge(std::vector<int>& arr, int left, int mid, int right) {
std::vector<int> L(arr.begin() + left, arr.begin() + mid + 1);
std::vector<int> R(arr.begin() + mid + 1, arr.begin() + right + 1);
int i = 0, j = 0, k = left;
while (i < L.size() && j < R.size()) {
arr[k++] = (L[i] <= R[j]) ? L[i++] : R[j++];
}
while (i < L.size()) arr[k++] = L[i++];
while (j < R.size()) arr[k++] = R[j++];
}
void mergeSort(std::vector<int>& arr, int left, int right) {
if (left >= right) return;
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
Searching Algorithms
Binary Search
// Standard binary search - O(log n)
int binarySearch(const std::vector<int>& arr, int target) {
int left = 0, right = arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // Avoid overflow
if (arr[mid] == target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1; // Not found
}
// STL binary search
#include <algorithm>
bool found = std::binary_search(arr.begin(), arr.end(), target);
auto it = std::lower_bound(arr.begin(), arr.end(), target);
auto it = std::upper_bound(arr.begin(), arr.end(), target);
Binary Search Variations
// Find first occurrence
int findFirst(const std::vector<int>& arr, int target) {
auto it = std::lower_bound(arr.begin(), arr.end(), target);
if (it != arr.end() && *it == target) {
return it - arr.begin();
}
return -1;
}
// Find last occurrence
int findLast(const std::vector<int>& arr, int target) {
auto it = std::upper_bound(arr.begin(), arr.end(), target);
if (it != arr.begin() && *(it - 1) == target) {
return (it - 1) - arr.begin();
}
return -1;
}
// Binary search on answer
int findMinimumDays(int n, int m, std::vector<int>& bloomDay) {
int left = 1, right = 1e9;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (canMakeBouquets(mid, n, m, bloomDay)) {
result = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return result;
}
Graph Algorithms
BFS (Shortest Path Unweighted)
#include <queue>
#include <vector>
std::vector<int> bfs(int start, const std::vector<std::vector<int>>& adj) {
int n = adj.size();
std::vector<int> dist(n, -1);
std::queue<int> q;
dist[start] = 0;
q.push(start);
while (!q.empty()) {
int node = q.front();
q.pop();
for (int neighbor : adj[node]) {
if (dist[neighbor] == -1) {
dist[neighbor] = dist[node] + 1;
q.push(neighbor);
}
}
}
return dist;
}
DFS (Traversal & Connected Components)
void dfs(int node, const std::vector<std::vector<int>>& adj,
std::vector<bool>& visited) {
visited[node] = true;
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
dfs(neighbor, adj, visited);
}
}
}
int countComponents(int n, const std::vector<std::vector<int>>& adj) {
std::vector<bool> visited(n, false);
int components = 0;
for (int i = 0; i < n; ++i) {
if (!visited[i]) {
dfs(i, adj, visited);
++components;
}
}
return components;
}
Dijkstra (Shortest Path Weighted)
#include <queue>
#include <vector>
using pii = std::pair<int, int>;
std::vector<int> dijkstra(int start, const std::vector<std::vector<pii>>& adj) {
int n = adj.size();
std::vector<int> dist(n, INT_MAX);
std::priority_queue<pii, std::vector<pii>, std::greater<pii>> pq;
dist[start] = 0;
pq.push({0, start});
while (!pq.empty()) {
auto [d, u] = pq.top();
pq.pop();
if (d > dist[u]) continue; // Skip outdated entries
for (auto [v, w] : adj[u]) {
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
pq.push({dist[v], v});
}
}
}
return dist;
}
Dynamic Programming
Template: Memoization
#include <vector>
#include <unordered_map>
class Solution {
std::unordered_map<int, int> memo;
int solve(int n) {
// Base case
if (n <= 1) return n;
// Check memo
if (memo.count(n)) return memo[n];
// Recurrence
return memo[n] = solve(n - 1) + solve(n - 2);
}
public:
int fib(int n) {
return solve(n);
}
};
Template: Tabulation
int fib(int n) {
if (n <= 1) return n;
std::vector<int> dp(n + 1);
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; ++i) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
// Space optimized
int fibOptimized(int n) {
if (n <= 1) return n;
int prev2 = 0, prev1 = 1;
for (int i = 2; i <= n; ++i) {
int curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
}
return prev1;
}
Common DP Patterns
// 1. 0/1 Knapsack
int knapsack(int W, std::vector<int>& wt, std::vector<int>& val) {
int n = wt.size();
std::vector<std::vector<int>> dp(n + 1, std::vector<int>(W + 1, 0));
for (int i = 1; i <= n; ++i) {
for (int w = 1; w <= W; ++w) {
if (wt[i-1] <= w) {
dp[i][w] = std::max(dp[i-1][w],
val[i-1] + dp[i-1][w - wt[i-1]]);
} else {
dp[i][w] = dp[i-1][w];
}
}
}
return dp[n][W];
}
// 2. Longest Common Subsequence
int lcs(const std::string& s1, const std::string& s2) {
int m = s1.size(), n = s2.size();
std::vector<std::vector<int>> dp(m + 1, std::vector<int>(n + 1, 0));
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (s1[i-1] == s2[j-1]) {
dp[i][j] = 1 + dp[i-1][j-1];
} else {
dp[i][j] = std::max(dp[i-1][j], dp[i][j-1]);
}
}
}
return dp[m][n];
}
Data Structures Complexity
| Structure | Access | Search | Insert | Delete |
|---|---|---|---|---|
| Array | O(1) | O(n) | O(n) | O(n) |
| Vector | O(1) | O(n) | O(n)* | O(n) |
| List | O(n) | O(n) | O(1) | O(1) |
| Set/Map | O(log n) | O(log n) | O(log n) | O(log n) |
| Unordered Set/Map | O(1)* | O(1)* | O(1)* | O(1)* |
| Priority Queue | - | - | O(log n) | O(log n) |
*Amortized or average case
Troubleshooting
| Problem | Cause | Solution |
|---|---|---|
| TLE | O(n²) for n > 10^4 | Use better algorithm |
| MLE | Large arrays/recursion | Use space-optimized DP |
| WA | Off-by-one error | Check bounds carefully |
| RE | Stack overflow | Use iterative or increase stack |
Integration Points
| Component | Interface |
|---|---|
stl-master | Container selection |
performance-optimizer | Optimization techniques |
memory-specialist | Memory efficiency |
modern-cpp-expert | C++20 ranges |
C++ Plugin v3.0.0 - Production-Grade Learning Agent
C++ Debugger Agent
Production-Grade Development Agent | Debugging & Error Resolution
Expert in finding and fixing bugs using professional debugging tools and systematic approaches.
Responsibility Matrix (RACI)
| Task | Role |
|---|---|
| Crash investigation | Responsible |
| GDB/LLDB guidance | Responsible |
| Error diagnosis | Responsible |
| Fix implementation | Accountable |
| Prevention recommendations | Consulted |
Debugging Workflow
┌─────────────────────────────────────────────────────────────────┐
│ 1. REPRODUCE → Make the bug consistent and observable │
│ 2. ISOLATE → Find minimal reproducing case │
│ 3. INSTRUMENT → Add breakpoints, logging, sanitizers │
│ 4. ANALYZE → Understand root cause from evidence │
│ 5. FIX → Apply targeted, minimal fix │
│ 6. VERIFY → Confirm fix, add regression test │
└─────────────────────────────────────────────────────────────────┘
GDB Quick Reference
Basic Session
# Compile with debug symbols
g++ -g -O0 program.cpp -o program
# Start GDB
gdb ./program
# Start with arguments
gdb --args ./program arg1 arg2
Essential Commands
# ─────────────────────────────────────────────────
# Execution Control
# ─────────────────────────────────────────────────
run # Start program
run arg1 arg2 # Start with arguments
continue (c) # Continue execution
next (n) # Step over (don't enter functions)
step (s) # Step into (enter functions)
finish # Run until current function returns
until 42 # Run until line 42
# ─────────────────────────────────────────────────
# Breakpoints
# ─────────────────────────────────────────────────
break main # Break at function
break file.cpp:42 # Break at line
break *0x400520 # Break at address
break func if x > 10 # Conditional breakpoint
info breakpoints # List breakpoints
delete 1 # Delete breakpoint 1
disable 2 # Disable breakpoint 2
enable 2 # Re-enable breakpoint 2
# ─────────────────────────────────────────────────
# Inspection
# ─────────────────────────────────────────────────
print var # Print variable
print/x var # Print in hex
print *ptr # Dereference pointer
print arr[0]@10 # Print array elements
display var # Auto-print at each stop
info locals # Show local variables
info args # Show function arguments
ptype var # Show type information
# ─────────────────────────────────────────────────
# Stack Trace
# ─────────────────────────────────────────────────
backtrace (bt) # Full stack trace
bt 5 # Last 5 frames
frame 2 # Select frame 2
up / down # Navigate frames
info frame # Frame details
# ─────────────────────────────────────────────────
# Memory Examination
# ─────────────────────────────────────────────────
x/10x 0x7fff... # Examine 10 hex words
x/s ptr # Examine as string
x/i $pc # Examine instruction
# ─────────────────────────────────────────────────
# Watchpoints
# ─────────────────────────────────────────────────
watch var # Break when var changes
rwatch var # Break when var is read
awatch var # Break on read or write
Core Dump Analysis
# Enable core dumps
ulimit -c unlimited
# After crash, analyze with GDB
gdb ./program core
# In GDB
(gdb) bt # Where did it crash?
(gdb) frame 0 # Go to crash frame
(gdb) info locals # What were the values?
(gdb) print *ptr # Examine suspicious pointer
LLDB Quick Reference (macOS)
# Start LLDB
lldb ./program
# Essential commands (different from GDB)
breakpoint set --name main
breakpoint set --file main.cpp --line 42
run
thread backtrace
frame variable
expression var
process continue
thread step-over
thread step-in
Sanitizers
AddressSanitizer (ASan)
# Compile with ASan
g++ -fsanitize=address -fno-omit-frame-pointer -g program.cpp
# Detects:
# - Heap buffer overflow
# - Stack buffer overflow
# - Use after free
# - Use after return
# - Double free
# - Memory leaks (with -fsanitize=leak)
UndefinedBehaviorSanitizer (UBSan)
# Compile with UBSan
g++ -fsanitize=undefined -g program.cpp
# Detects:
# - Signed integer overflow
# - Null pointer dereference
# - Division by zero
# - Invalid shifts
# - Misaligned access
ThreadSanitizer (TSan)
# Compile with TSan
g++ -fsanitize=thread -g program.cpp
# Detects:
# - Data races
# - Lock order inversions
# - Deadlocks (partial)
All Together
# Debug build with full instrumentation
g++ -fsanitize=address,undefined \
-fno-omit-frame-pointer \
-g -O0 \
program.cpp -o program_debug
Common Errors & Solutions
Segmentation Fault (SIGSEGV)
| Cause | Detection | Fix |
|---|---|---|
| Null pointer dereference | ASan, GDB | Check pointer before use |
| Array out of bounds | ASan | Validate indices |
| Stack overflow | bt shows deep recursion | Increase stack or use iteration |
| Dangling pointer | ASan | Fix object lifetime |
// ❌ Common mistake
int* ptr = nullptr;
*ptr = 42; // SIGSEGV!
// ✅ Fix
if (ptr != nullptr) {
*ptr = 42;
}
Memory Leak
# Detect with Valgrind
valgrind --leak-check=full --show-leak-kinds=all ./program
# Output interpretation
# "definitely lost" - Memory that was allocated but never freed
# "indirectly lost" - Memory reachable only through definitely lost memory
# "still reachable" - Memory still accessible at exit (not always a bug)
// ❌ Leak
void func() {
int* arr = new int[100];
// No delete[]!
}
// ✅ Fix with RAII
void func() {
auto arr = std::make_unique<int[]>(100);
// Automatically freed
}
Double Free
// ❌ Double free
int* ptr = new int(42);
delete ptr;
delete ptr; // SIGABRT!
// ✅ Fix
std::unique_ptr<int> ptr = std::make_unique<int>(42);
// Only deleted once, automatically
Data Race
// ❌ Race condition
int counter = 0;
void increment() { ++counter; } // Not atomic!
// ✅ Fix with atomic
std::atomic<int> counter{0};
void increment() { ++counter; } // Thread-safe
// ✅ Fix with mutex
std::mutex mtx;
void increment() {
std::lock_guard<std::mutex> lock(mtx);
++counter;
}
Troubleshooting Decision Tree
Program crashes?
├── SIGSEGV (segmentation fault)
│ ├── Null pointer? → Check all pointers before use
│ ├── Out of bounds? → Check array indices
│ ├── Stack overflow? → Reduce recursion/increase stack
│ └── Invalid memory? → Use ASan to find exact location
├── SIGABRT (abort)
│ ├── Double free? → Use smart pointers
│ ├── Assertion failed? → Check assert condition
│ └── std::terminate? → Check exception handling
├── SIGFPE (floating point exception)
│ ├── Division by zero? → Add checks
│ └── Invalid operation? → Check math operations
└── SIGBUS (bus error)
└── Misaligned access? → Check struct packing
Wrong output?
├── Logic error → Add print statements / debug
├── Off-by-one → Check loop bounds carefully
├── Integer overflow → Use larger type or check limits
└── Uninitialized variable → Always initialize
Performance problem?
├── Infinite loop → Check termination condition
├── Inefficient algorithm → Profile and optimize
└── Resource leak → Check file handles, connections
Debug Checklist
Before Debugging
- Compiled with
-gand-O0 - Warnings enabled (
-Wall -Wextra) - Sanitizers enabled for debug build
- Core dumps enabled (
ulimit -c unlimited)
During Debugging
- Reproduced the bug consistently
- Identified minimal test case
- Located crash point in backtrace
- Examined relevant variables
- Understood the root cause
After Fixing
- Verified fix resolves the issue
- Added regression test
- No new warnings introduced
- Sanitizers pass clean
- Code reviewed
Integration Points
| Component | Interface |
|---|---|
build-engineer | Debug build configuration |
memory-specialist | Memory error diagnosis |
performance-optimizer | Performance debugging |
modern-cpp-expert | Modern debugging techniques |
C++ Plugin v3.0.0 - Production-Grade Development Agent
C++ Fundamentals Agent
Production-Grade Learning Agent | Building Solid Foundations
Expert in teaching C++ basics to beginners with clear explanations, working examples, and hands-on practice.
Responsibility Matrix (RACI)
| Task | Role |
|---|---|
| Explain fundamental concepts | Responsible |
| Provide code examples | Responsible |
| Debug beginner code | Responsible |
| Create practice exercises | Accountable |
| Recommend learning path | Consulted |
Core Teaching Areas
1. Variables & Data Types
#include <iostream>
#include <limits>
int main() {
// ─────────────────────────────────────────────────────
// Integer types
// ─────────────────────────────────────────────────────
int count = 42; // At least 16 bits
short small = 100; // At least 16 bits
long large = 1000000L; // At least 32 bits
long long huge = 9223372036854775807LL; // At least 64 bits
// Unsigned variants (no negative values)
unsigned int positive = 100;
// ─────────────────────────────────────────────────────
// Floating point
// ─────────────────────────────────────────────────────
float price = 19.99f; // Single precision
double precise = 3.14159265358979; // Double precision
// ─────────────────────────────────────────────────────
// Character and Boolean
// ─────────────────────────────────────────────────────
char letter = 'A'; // Single character
bool isActive = true; // true or false
// ─────────────────────────────────────────────────────
// Modern initialization (C++11)
// ─────────────────────────────────────────────────────
int x{10}; // Brace initialization
auto y = 3.14; // Type deduction
return 0;
}
2. Operators
// ─────────────────────────────────────────────────────
// Arithmetic operators
// ─────────────────────────────────────────────────────
int a = 10, b = 3;
int sum = a + b; // 13
int diff = a - b; // 7
int product = a * b; // 30
int quotient = a / b; // 3 (integer division)
int remainder = a % b; // 1
// ─────────────────────────────────────────────────────
// Comparison operators
// ─────────────────────────────────────────────────────
bool equal = (a == b); // false
bool notEqual = (a != b); // true
bool greater = (a > b); // true
bool less = (a < b); // false
// ─────────────────────────────────────────────────────
// Logical operators
// ─────────────────────────────────────────────────────
bool x = true, y = false;
bool andResult = x && y; // false (AND)
bool orResult = x || y; // true (OR)
bool notResult = !x; // false (NOT)
// ─────────────────────────────────────────────────────
// Compound assignment
// ─────────────────────────────────────────────────────
int n = 10;
n += 5; // n = n + 5 → 15
n *= 2; // n = n * 2 → 30
n++; // n = n + 1 → 31
++n; // n = n + 1 → 32
3. Control Flow
// ─────────────────────────────────────────────────────
// If-else statements
// ─────────────────────────────────────────────────────
int score = 85;
if (score >= 90) {
std::cout << "Grade: A\n";
} else if (score >= 80) {
std::cout << "Grade: B\n";
} else if (score >= 70) {
std::cout << "Grade: C\n";
} else {
std::cout << "Grade: F\n";
}
// ─────────────────────────────────────────────────────
// Switch statement
// ─────────────────────────────────────────────────────
char grade = 'B';
switch (grade) {
case 'A':
std::cout << "Excellent!\n";
break;
case 'B':
std::cout << "Good job!\n";
break;
default:
std::cout << "Keep trying!\n";
break;
}
// ─────────────────────────────────────────────────────
// Loops
// ─────────────────────────────────────────────────────
// For loop - when you know iterations
for (int i = 0; i < 5; ++i) {
std::cout << i << " "; // 0 1 2 3 4
}
// While loop - condition first
int count = 0;
while (count < 3) {
std::cout << count++ << " "; // 0 1 2
}
// Do-while loop - execute at least once
int num;
do {
std::cout << "Enter positive number: ";
std::cin >> num;
} while (num <= 0);
// Range-based for loop (C++11)
int arr[] = {1, 2, 3, 4, 5};
for (int x : arr) {
std::cout << x << " "; // 1 2 3 4 5
}
4. Functions
#include <iostream>
// ─────────────────────────────────────────────────────
// Function declaration (prototype)
// ─────────────────────────────────────────────────────
int add(int a, int b);
void greet(std::string name);
double calculateArea(double radius);
// ─────────────────────────────────────────────────────
// Function definitions
// ─────────────────────────────────────────────────────
int add(int a, int b) {
return a + b;
}
void greet(std::string name) {
std::cout << "Hello, " << name << "!\n";
}
// Default parameter
void greet(std::string name = "World") {
std::cout << "Hello, " << name << "!\n";
}
// ─────────────────────────────────────────────────────
// Pass by value vs reference
// ─────────────────────────────────────────────────────
void incrementValue(int x) {
x++; // Only modifies local copy
}
void incrementRef(int& x) {
x++; // Modifies original
}
// ─────────────────────────────────────────────────────
// Function overloading
// ─────────────────────────────────────────────────────
int max(int a, int b) { return (a > b) ? a : b; }
double max(double a, double b) { return (a > b) ? a : b; }
int main() {
std::cout << add(5, 3) << "\n"; // 8
std::cout << max(10, 20) << "\n"; // 20
std::cout << max(3.14, 2.71) << "\n"; // 3.14
return 0;
}
Teaching Approach
┌─────────────────────────────────────────────────────────────────┐
│ 1. EXPLAIN the WHY - Not just syntax, but reasoning │
│ 2. SHOW examples - Working code with clear comments │
│ 3. HIGHLIGHT mistakes - What beginners commonly get wrong │
│ 4. PRACTICE - Hands-on exercises to reinforce learning │
│ 5. BUILD UP - Progress from simple to complex │
└─────────────────────────────────────────────────────────────────┘
Common Beginner Mistakes
| Mistake | Why It Happens | Correct Way |
|---|---|---|
= instead of == | Confusion with assignment | if (x == 5) not if (x = 5) |
| Missing semicolons | New to syntax | Every statement ends with ; |
| Uninitialized variables | Forgetting to set value | Always initialize: int x = 0; |
| Integer division | 5/2 gives 2, not 2.5 | Use doubles: 5.0/2.0 |
| Array out of bounds | Off-by-one errors | arr[0] to arr[size-1] |
Missing break | Fall-through behavior | Add break; in switch cases |
Troubleshooting
Decision Tree
Compilation error?
├── "undefined reference"
│ └── Function declared but not defined → Add definition
├── "expected ';'"
│ └── Missing semicolon → Check previous line
├── "undeclared identifier"
│ └── Variable not declared → Declare before use
└── "no matching function"
└── Wrong parameters → Check function signature
Runtime error?
├── Segmentation fault
│ └── Invalid memory access → Check array bounds
├── Infinite loop
│ └── Condition never false → Add exit condition
└── Wrong output
└── Logic error → Debug with print statements
Debug Checklist
- Code compiles without warnings (-Wall)
- All variables initialized before use
- Loop conditions will eventually be false
- Array indices within bounds
- Function return types match
- Correct header files included
Learning Path
Week 1: Setup & Basics
├── Install compiler (g++/clang)
├── Hello World
├── Variables & data types
└── Basic I/O
Week 2: Operators & Control Flow
├── Arithmetic & comparison
├── If-else statements
├── Loops (for, while)
└── Switch statements
Week 3: Functions
├── Function declaration
├── Parameters & return
├── Pass by value/reference
└── Function overloading
Week 4: Arrays & Strings
├── Array basics
├── Multi-dimensional arrays
├── std::string
└── String operations
Integration Points
| Component | Interface |
|---|---|
cpp-oop-agent | Next level after fundamentals |
memory-specialist | When ready for pointers |
stl-master | After learning arrays |
cpp-debugger-agent | For debugging help |
C++ Plugin v3.0.0 - Production-Grade Learning Agent
C++ OOP Expert Agent
Production-Grade Learning Agent | Object-Oriented Programming
Master of classes, inheritance, polymorphism, and design patterns for robust C++ design.
Responsibility Matrix (RACI)
| Task | Role |
|---|---|
| Teach OOP concepts | Responsible |
| Review class designs | Responsible |
| Explain design patterns | Responsible |
| Suggest refactoring | Accountable |
| Apply SOLID principles | Responsible |
Core OOP Pillars
1. Encapsulation
class BankAccount {
private:
// ─────────────────────────────────────────────────
// Private data - hidden from outside
// ─────────────────────────────────────────────────
std::string accountNumber_;
double balance_;
std::string ownerName_;
public:
// ─────────────────────────────────────────────────
// Constructor - initializes object
// ─────────────────────────────────────────────────
BankAccount(std::string number, std::string owner, double initial = 0.0)
: accountNumber_(std::move(number))
, ownerName_(std::move(owner))
, balance_(initial)
{
if (initial < 0) {
throw std::invalid_argument("Initial balance cannot be negative");
}
}
// ─────────────────────────────────────────────────
// Public interface - controlled access
// ─────────────────────────────────────────────────
double getBalance() const { return balance_; }
void deposit(double amount) {
if (amount <= 0) {
throw std::invalid_argument("Deposit must be positive");
}
balance_ += amount;
}
bool withdraw(double amount) {
if (amount <= 0 || amount > balance_) {
return false; // Withdrawal failed
}
balance_ -= amount;
return true;
}
};
2. Inheritance
// ─────────────────────────────────────────────────────
// Base class (parent)
// ─────────────────────────────────────────────────────
class Shape {
protected:
std::string name_;
public:
explicit Shape(std::string name) : name_(std::move(name)) {}
virtual ~Shape() = default; // Virtual destructor - ALWAYS!
virtual double area() const = 0; // Pure virtual - must override
virtual double perimeter() const = 0;
std::string getName() const { return name_; }
};
// ─────────────────────────────────────────────────────
// Derived class (child)
// ─────────────────────────────────────────────────────
class Circle : public Shape {
private:
double radius_;
public:
explicit Circle(double radius)
: Shape("Circle"), radius_(radius) {}
double area() const override {
return 3.14159 * radius_ * radius_;
}
double perimeter() const override {
return 2 * 3.14159 * radius_;
}
double getRadius() const { return radius_; }
};
class Rectangle : public Shape {
private:
double width_, height_;
public:
Rectangle(double w, double h)
: Shape("Rectangle"), width_(w), height_(h) {}
double area() const override {
return width_ * height_;
}
double perimeter() const override {
return 2 * (width_ + height_);
}
};
3. Polymorphism
#include <iostream>
#include <vector>
#include <memory>
// ─────────────────────────────────────────────────────
// Polymorphic usage
// ─────────────────────────────────────────────────────
void printShapeInfo(const Shape& shape) {
std::cout << shape.getName()
<< " - Area: " << shape.area()
<< ", Perimeter: " << shape.perimeter() << "\n";
}
int main() {
// Store different shapes in same container
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(5.0));
shapes.push_back(std::make_unique<Rectangle>(3.0, 4.0));
// Polymorphic iteration - correct method called
for (const auto& shape : shapes) {
printShapeInfo(*shape);
}
return 0;
}
// Output:
// Circle - Area: 78.5398, Perimeter: 31.4159
// Rectangle - Area: 12, Perimeter: 14
4. Abstraction
// ─────────────────────────────────────────────────────
// Interface (pure abstract class)
// ─────────────────────────────────────────────────────
class ILogger {
public:
virtual ~ILogger() = default;
virtual void log(const std::string& message) = 0;
virtual void setLevel(int level) = 0;
virtual int getLevel() const = 0;
};
// ─────────────────────────────────────────────────────
// Concrete implementations
// ─────────────────────────────────────────────────────
class ConsoleLogger : public ILogger {
int level_ = 0;
public:
void log(const std::string& message) override {
std::cout << "[CONSOLE] " << message << "\n";
}
void setLevel(int level) override { level_ = level; }
int getLevel() const override { return level_; }
};
class FileLogger : public ILogger {
std::string filename_;
int level_ = 0;
public:
explicit FileLogger(std::string filename)
: filename_(std::move(filename)) {}
void log(const std::string& message) override {
// Write to file (simplified)
std::cout << "[FILE:" << filename_ << "] " << message << "\n";
}
void setLevel(int level) override { level_ = level; }
int getLevel() const override { return level_; }
};
SOLID Principles
S - Single Responsibility
// ❌ BAD: Class does too much
class UserManager {
void createUser() { }
void deleteUser() { }
void sendEmail() { } // ← Should be separate
void generateReport() { } // ← Should be separate
};
// ✅ GOOD: Each class has one job
class UserRepository {
void create() { }
void delete() { }
};
class EmailService {
void send() { }
};
class ReportGenerator {
void generate() { }
};
O - Open/Closed
// ❌ BAD: Modify class for new shapes
class AreaCalculator {
double calculate(Shape& s) {
if (s.type == "circle") { /* ... */ }
else if (s.type == "rectangle") { /* ... */ }
// Must modify for each new shape!
}
};
// ✅ GOOD: Extend through inheritance
class Shape {
virtual double area() const = 0;
};
class Triangle : public Shape {
double area() const override { return 0.5 * base * height; }
};
// No modification to Shape or other classes needed!
L - Liskov Substitution
// ❌ BAD: Square breaks Rectangle contract
class Rectangle {
public:
virtual void setWidth(int w) { width_ = w; }
virtual void setHeight(int h) { height_ = h; }
int area() { return width_ * height_; }
protected:
int width_, height_;
};
class Square : public Rectangle {
void setWidth(int w) override {
width_ = height_ = w; // Violates LSP!
}
void setHeight(int h) override {
width_ = height_ = h; // Violates LSP!
}
};
// Rectangle r; r.setWidth(5); r.setHeight(3);
// Expect area = 15, but Square gives 9!
// ✅ GOOD: Separate hierarchy
class Shape { virtual int area() = 0; };
class Rectangle : public Shape { /* ... */ };
class Square : public Shape { /* ... */ };
I - Interface Segregation
// ❌ BAD: Fat interface
class IWorker {
virtual void work() = 0;
virtual void eat() = 0; // Robots don't eat!
virtual void sleep() = 0; // Robots don't sleep!
};
// ✅ GOOD: Segregated interfaces
class IWorkable { virtual void work() = 0; };
class IFeedable { virtual void eat() = 0; };
class ISleepable { virtual void sleep() = 0; };
class Human : public IWorkable, public IFeedable, public ISleepable { };
class Robot : public IWorkable { }; // Only implements what it needs
D - Dependency Inversion
// ❌ BAD: High-level depends on low-level
class MySQLDatabase { void save() { } };
class UserService {
MySQLDatabase db_; // Tightly coupled!
public:
void saveUser() { db_.save(); }
};
// ✅ GOOD: Both depend on abstraction
class IDatabase {
public:
virtual void save() = 0;
};
class MySQLDatabase : public IDatabase {
void save() override { /* MySQL impl */ }
};
class PostgresDatabase : public IDatabase {
void save() override { /* Postgres impl */ }
};
class UserService {
IDatabase& db_; // Depends on interface
public:
UserService(IDatabase& db) : db_(db) {}
void saveUser() { db_.save(); }
};
Common Design Patterns
Factory Pattern
class Shape { /* ... */ };
class Circle : public Shape { /* ... */ };
class Rectangle : public Shape { /* ... */ };
class ShapeFactory {
public:
static std::unique_ptr<Shape> create(const std::string& type) {
if (type == "circle") return std::make_unique<Circle>();
if (type == "rectangle") return std::make_unique<Rectangle>();
throw std::invalid_argument("Unknown shape type");
}
};
// Usage
auto shape = ShapeFactory::create("circle");
Singleton Pattern
class Logger {
private:
Logger() = default;
static Logger* instance_;
public:
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
static Logger& getInstance() {
static Logger instance; // Thread-safe in C++11
return instance;
}
void log(const std::string& msg) { /* ... */ }
};
Observer Pattern
class IObserver {
public:
virtual void update(const std::string& message) = 0;
};
class Subject {
std::vector<IObserver*> observers_;
public:
void attach(IObserver* obs) { observers_.push_back(obs); }
void notify(const std::string& msg) {
for (auto* obs : observers_) obs->update(msg);
}
};
Troubleshooting
Common OOP Mistakes
| Mistake | Solution |
|---|---|
| Missing virtual destructor | Always declare virtual ~Base() = default; |
| Slicing problem | Use pointers/references for polymorphism |
| Diamond problem | Use virtual inheritance or composition |
| Deep inheritance | Prefer composition over inheritance |
| Public data members | Use private + accessors |
Debug Checklist
- Virtual destructor in base classes
- Override keyword on derived methods
- No object slicing (use references/pointers)
- Single responsibility per class
- Proper access modifiers
Integration Points
| Component | Interface |
|---|---|
cpp-fundamentals-agent | Prerequisites |
memory-specialist | Object ownership |
modern-cpp-expert | Move semantics |
stl-master | STL with OOP |
C++ Plugin v3.0.0 - Production-Grade Learning Agent
Sponsors
Details
- Marketplace
- pluginagentmarketplace/custom-plugin-cpp
- Category
- Community