— No reviews yet
0 installs
18 views
0.0% view→install
Install
$ agentstack add skill-softspark-ai-toolkit-cpp-rules ✓ scanned · ✓ verified — works with Claude Code, Cursor, and more.
Security review
✓ PassedNo issues found. Passed automated security review. · v0.1.0 How review works →
- ✓ Prompt-injection patterns
- ✓ Secret / credential exfiltration
- ✓ Dangerous shell & filesystem operations
- ✓ Untrusted network calls
- ✓ Known-malicious package signatures
What it can access
- ● Network access Used
- ● Filesystem access Used
- ✓ Shell / process execution No
- ✓ Environment & secrets No
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
Are you the author of Cpp Rules? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claimAbout
C++ Rules
These rules come from app/rules/cpp/ in ai-toolkit. They cover the project's standards for coding style, frameworks, patterns, security, and testing in C++. Apply them when writing or reviewing C++ code.
C++ Coding Style
Naming
- PascalCase: classes, structs, enums, type aliases, concepts.
- camelCase or snake_case: functions, methods, variables (be consistent per project).
- UPPER_SNAKE: macros, compile-time constants.
- Prefix member variables with
m_or suffix with_(pick one convention). - Namespace names: lowercase, short (
namespace io,namespace util).
Modern C++ (17/20/23)
- Use
autofor iterator types and complex template deductions. - Use
std::optionalinstead of sentinel values or pointers for optional returns. - Use
std::variantover union types. Usestd::visitfor dispatch. - Use
std::string_viewfor non-owning string parameters. - Use structured bindings:
auto [key, value] = *map.begin();. - Use
constexprfor compile-time evaluation. Prefer over macros.
Memory Management
- Use RAII exclusively. Every resource acquisition is an initialization.
- Use
std::unique_ptrfor exclusive ownership (default choice). - Use
std::shared_ptronly when ownership is genuinely shared. - Never use raw
new/delete. Usestd::make_unique/std::make_shared. - Use
std::span(C++20) for non-owning views over contiguous data.
Functions
- Pass small types by value. Pass large types by
const&. - Use
[[nodiscard]]on functions whose return value must not be ignored. - Use
noexcepton functions that do not throw (move constructors, destructors). - Limit function parameters to 4. Use structs for configuration objects.
- Use trailing return types for complex template return deductions.
Includes and Dependencies
- Use
#pragma onceor include guards. Prefer#pragma oncefor simplicity. - Order: corresponding header, C++ stdlib, third-party, project headers.
- Forward-declare in headers when possible to reduce compile times.
- Minimize header dependencies. Use the Pimpl idiom for ABI stability.
Avoid
- Raw pointers for ownership. Use smart pointers.
- C-style casts. Use
static_cast,dynamic_cast,const_cast. - Macros for constants or functions. Use
constexprand templates. using namespace std;in headers. Acceptable in .cpp files with caution.std::endl-- use'\n'(endl flushes the buffer unnecessarily).
Formatting
- Use clang-format with a committed
.clang-formatfile. - Use clang-tidy for static analysis and automated modernization.
- Max line length: 100-120 characters.
- Braces: use Allman or K&R consistently per project.
C++ Frameworks
CMake
- Use modern CMake (3.14+): target-based, not directory-based.
- Use
target_link_librarieswithPUBLIC/PRIVATE/INTERFACEvisibility. - Use
FetchContentfor dependency management. Avoid manual submodule vendoring. - Set
CMAKE_CXX_STANDARD 20(or 23) at the project level. - Use
target_compile_optionsfor per-target flags, not globaladd_compile_options. - Export targets with
install(TARGETS ... EXPORT ...)for library consumers.
Boost
- Use Boost.Asio for async networking and I/O.
- Use
boost::beastfor HTTP/WebSocket built on Asio. - Use
boost::jsonornlohmann/jsonfor JSON parsing. - Prefer C++ stdlib equivalents when available (e.g.,
std::optionaloverboost::optional). - Link only the Boost libraries you actually use. Many are header-only.
Qt
- Use signals and slots for event-driven communication.
- Use
QObjectparent-child ownership for automatic memory management. - Use
QMLfor declarative UI. Keep business logic in C++ backend. - Use
QThreadwith worker objects (moveToThread), not subclassing QThread. - Use smart pointers for non-QObject resources. QObject children are auto-deleted.
gRPC
- Define services in
.protofiles. Generate C++ stubs withprotoc. - Use async server with
CompletionQueuefor high-throughput services. - Use
grpc::ClientContextfor per-call deadlines and metadata. - Use interceptors for logging, auth, and metrics.
- Set deadlines on every RPC call to prevent hanging.
Networking (Asio)
- Use
io_contextas the event loop. Run from one or more threads. - Use
co_await(C++20 coroutines) with Asio for clean async code. - Use
strandfor serializing access to shared state across handlers. - Use
steady_timerfor timeouts and periodic tasks. - Handle errors via
error_codeparameter, not exceptions, in async callbacks.
Database
- Use
libpq(PostgreSQL) orSOCIfor database access. - Use prepared statements exclusively. Never concatenate SQL strings.
- Use connection pooling for multi-threaded server applications.
- Use
SQLiteviasqlite3C API with RAII wrappers for embedded use cases.
Package Management
- Use
vcpkgorConan 2for dependency management. - Pin dependency versions in
vcpkg.jsonorconanfile.py. - Use CI caching for build artifacts and dependency downloads.
- Prefer pre-built binary packages for CI speed.
C++ Patterns
Error Handling
- Use exceptions for truly exceptional conditions. Use return types for expected failures.
- Use
std::expected(C++23) orResultpattern for recoverable errors. - Use
std::error_code/std::error_categoryfor system-level errors. - Use
noexcepton functions that must not throw (destructors, move operations). - Catch by
const&. Never catch by value (slicing) or pointer.
RAII Patterns
- Wrap every resource (memory, file, lock, socket) in an RAII type.
- Use
std::lock_guardorstd::scoped_lockfor mutex management. - Use
std::unique_lockwhen deferred locking or condition variables are needed. - Use
std::fstream(auto-closes) instead offopen/fclose. - Write custom RAII wrappers for C library resources (file descriptors, handles).
Smart Pointer Patterns
unique_ptr: default ownership model. Transfer withstd::move.shared_ptr: use only for genuinely shared ownership graphs.weak_ptr: break cycles inshared_ptrgraphs. Uselock()to access.- Factory functions should return
unique_ptr. Let callers upgrade toshared_ptr. - Never pass smart pointers by reference. Pass
T&orT*to non-owning consumers.
Concurrency
- Use
std::threadwithstd::jthread(C++20) for auto-joining threads. - Use
std::mutex+std::scoped_lockfor shared data protection. - Use
std::atomicfor lock-free single-variable synchronization. - Use
std::condition_variablefor producer-consumer patterns. - Use
std::async/std::futurefor simple parallel computation. - Use
std::counting_semaphore(C++20) for resource pool limiting.
Template Patterns
- Use CRTP for compile-time polymorphism (static dispatch).
- Use
concepts(C++20) to constrain template parameters with clear error messages. - Use
if constexprfor compile-time branching in templates. - Use variadic templates and fold expressions for parameter packs.
- Prefer
constexprfunctions over template metaprogramming when possible.
Design Patterns
- Use
std::variant+std::visitfor type-safe visitor pattern. - Use
std::functionfor type-erased callbacks and strategy pattern. - Use Pimpl idiom (
unique_ptr) for ABI stability and compilation firewall. - Use Builder pattern with method chaining for complex object construction.
- Use
std::movesemantics in move constructors for efficient resource transfer.
Anti-Patterns
- Raw
new/delete: use smart pointers and containers. - Returning raw pointers from factory functions: return
unique_ptr. const_castto remove constness: redesign the interface.- Deep inheritance hierarchies: prefer composition and templates.
- Premature optimization over readability: profile first, optimize second.
C++ Security
Buffer Overflow Prevention
- Use
std::string,std::vector,std::arrayinstead of C arrays andchar[]. - Use
std::span(C++20) for safe, bounds-checked views over contiguous data. - Never use
strcpy,strcat,sprintf. Usestd::stringoperations orsnprintf. - Enable
-D_FORTIFY_SOURCE=2in release builds for runtime buffer checks. - Use
at()for bounds-checked container access in untrusted input paths.
Memory Safety
- Use smart pointers exclusively. Zero raw
new/deletein application code. - Enable AddressSanitizer (
-fsanitize=address) in development and CI builds. - Enable UndefinedBehaviorSanitizer (
-fsanitize=undefined) in test builds. - Use
-fstack-protector-strongfor stack buffer overflow detection. - Use Valgrind for memory leak detection in integration tests.
Integer Safety
- Check for overflow before arithmetic on untrusted integers.
- Use
std::numeric_limits::max()for boundary checks. - Use unsigned types only for bit manipulation. Prefer signed for arithmetic.
- Use
static_castexplicitly. Never rely on implicit narrowing conversions. - Enable
-Wconversionand-Wsign-conversionwarnings.
Input Validation
- Validate all external input: file data, network packets, command-line arguments.
- Use
std::stoi/std::stolwith exception handling for string-to-number conversion. - Set maximum sizes for dynamic allocations based on untrusted input.
- Validate file paths to prevent directory traversal (
../). - Use allowlist validation for format specifiers and command strings.
Secure Coding
- Use
std::fillorexplicit_bzero()to zero sensitive memory before deallocation. - Use constant-time comparison for secrets (avoid timing side-channels).
- Use
mlock()to prevent sensitive memory from being swapped to disk. - Compile with
-fPIE -piefor position-independent executables (ASLR). - Enable
-Werrorin CI to prevent warnings from becoming vulnerabilities.
Dependencies
- Audit third-party C libraries for known CVEs before inclusion.
- Use
vcpkgorConanwith pinned versions for reproducible builds. - Prefer well-maintained libraries with active security response teams.
- Minimize C library usage. Prefer C++ standard library equivalents.
Concurrency Safety
- Use
std::mutexwithstd::scoped_lockfor all shared data access. - Use
std::atomicfor lock-free single-variable operations. - Enable ThreadSanitizer (
-fsanitize=thread) in test builds for race detection. - Avoid
volatilefor synchronization. It does not provide atomicity or ordering. - Use RAII lock guards. Never manually
lock()/unlock().
Compiler Hardening
- Enable all warnings:
-Wall -Wextra -Wpedantic. - Use
-D_GLIBCXX_ASSERTIONSfor debug iterator and container checks. - Use
-fno-exceptionsonly when exception safety is not required. - Link with
-Wl,-z,relro,-z,nowfor full RELRO (GOT hardening).
C++ Testing
Framework
- Use GoogleTest (gtest) as the primary test framework.
- Use GoogleMock (gmock) for mocking interfaces and virtual classes.
- Use Catch2 as a lightweight alternative (header-only, BDD-style).
- Use CTest for test discovery and execution via CMake.
File Naming
- Test files:
foo_test.cpportest_foo.cppin a dedicatedtests/directory. - Mirror source directory structure in test directory.
- One test file per source file or logical component.
- Use
CMakeLists.txtwithadd_test()to register tests.
Structure (GoogleTest)
- Use
TEST(SuiteName, TestName)for simple tests. - Use
TEST_F(FixtureName, TestName)for tests sharing setup/teardown. - Use
SetUp()/TearDown()in fixtures for per-test initialization. - Keep tests focused: one logical assertion per test case.
Assertions
- Use
EXPECT_*(non-fatal) by default. UseASSERT_*only when continuation is meaningless. EXPECT_EQ,EXPECT_NE,EXPECT_LT,EXPECT_GTfor comparisons.EXPECT_TRUE,EXPECT_FALSEfor boolean conditions.EXPECT_THROW(expr, ExceptionType)for exception testing.EXPECT_THAT(value, matcher)with gmock matchers for complex assertions.
Parameterized Tests
- Use
INSTANTIATE_TEST_SUITE_Pwithtesting::Values(...)for value-parameterized tests. - Use
testing::Combine()for multi-dimensional parameterization. - Use
TYPED_TEST_SUITEfor type-parameterized tests across template types. - Prefer parameterized tests over copy-pasting similar test bodies.
Mocking (GoogleMock)
- Define mock classes:
MOCK_METHOD(ReturnType, MethodName, (Args), (Qualifiers)). - Use
EXPECT_CALL(mock, Method(matchers)).WillOnce(Return(value)). - Use
NiceMockto suppress uninteresting call warnings. - Use
StrictMockto fail on any unexpected call. - Use dependency injection (constructor) to pass mock objects.
Build Integration
- Use
FetchContentorfind_packageto integrate gtest in CMake. - Enable
BUILD_TESTINGoption to conditionally include tests. - Use
ctest --output-on-failurefor CI runs. - Use sanitizers in test builds:
-fsanitize=address,undefined.
Best Practices
- Test edge cases: empty input, max values, null pointers, boundary conditions.
- Use RAII test fixtures for resource cleanup (no manual teardown).
- Avoid testing private methods directly. Test through public API.
- Use
valgrindor ASan/UBSan in CI to detect memory errors. - Keep tests fast: mock I/O and external dependencies.
Source & license
This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.
- Author: softspark
- Source: softspark/ai-toolkit
- License: MIT
- Homepage: https://softspark.eu
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet — be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.