TsukiNi22/ai-utils / skills/cpp/cpp-style
cpp-style
UnverifiedTsukini's personal C++ coding style (from libutils) - naming (PascalCase types, camelCase methods, _member, snake_case tools, UPPER macros), 4-space indentation, brace placement, spacing, one-liners, loops, switch, lambdas, const correctness, casts, attributes. Use whenever writing, editing, refactoring or reviewing C++ code (.cpp/.hpp) for the user, so the code looks like theirs.
Tsukini C++ coding style
Extracted from the recent libutils code (C++20, clang++, -W -Wall -Wextra -Wpedantic -Wshadow).
When editing an existing file, its local style wins over this document.
File/class layout (header, sections, blocks): the cpp-class skill. Comments: the cpp-comments skill.
Naming
| Element | Style | Examples |
|---|---|---|
| class / struct / enum / alias | PascalCase | IdHandler, ParsedUsage, ParsedUsages |
| interface / abstract | I / A prefix | ISocket, ASocket -> TCPSocket |
| method | camelCase, verb first | setPayloadSeparator, getFd, hasRecvOverload, resetUsages |
| private / protected / internal function (wrapper impl included) | <name>(<Name>)*_: camelCase + trailing _ | allocate_, cancel_, computeHash_, readChunkHeader_ |
| free tool function | snake_case | is_ip, resolve_hostname, rotate_point_3D |
| hook / callback function | camelCase | defaultHelpHook, defaultInt32ParsingHook |
| member | _camelCase | _usedIds, _helpHook, _fd |
| local variable / parameter | camelCase (bool included), short names fine in small scopes (i, j, f, it, e, s) | alreadyFailed, equalFound, argOrigin |
| special bool parameter (a mode / switch with a default value) | snake_case, only for these | const bool safe_mode = true, const bool ignore_case = false, failsafe |
| macro / define | UPPER_SNAKE | SOCKET_CHUNK_SIZE, OVERFLOW_LIMIT |
| attribute macro (libutils) | _lower | _hot, _nodiscard, _migration(4, 0, 0) |
| enum value | PascalCase, trailing comma | Status::Up, InternalCode::UnknownId |
| template parameter | T, Fn, <Name>T | template<typename T>, ByteT |
| namespace | lowercase, nested with :: | utils::network, utils::system |
| file | class name, or lowercase for a free-function module | IdHandler.hpp, format.hpp |
Getters getX(void) const, setters setX(...), boolean queries isX / hasX, removal removeX,
resetX to restore the default. Plural for collections (_options, removeFlags).
Indentation & braces
- 4 spaces, never tabs. No trailing whitespace. Lines can be long (no hard limit), but split conditions/arguments that become unreadable.
public:/private:/protected:indented by 4 inside the class, members by 8.- Out-of-line function / method / constructor: opening brace on its own line.
- Class, struct, enum, namespace,
if,else,for,while,switch,do, lambda: brace on the same line. } else {/} else if (...) {on the closing brace line.- Namespace content is not indented.
- Preprocessor conditionals (
#if/#ifdef/#ifndef/#elif/#else/#endif): the directive is at the indentation of the code around it, and everything it contains (code and directives) is indented one level (4 spaces) more. Never a directive at column 0 in the middle of indented code, never content left at the level of its directive:_cold int utils::platform::close(int fd) { #ifdef UTILS_WINDOWS if (fd < 0) _unlikely {errno = EBADF; return -1;} return ::_close(fd); #else return ::close(fd); #endif } class SharedMemory { private: void* _ptr = nullptr; #ifdef UTILS_WINDOWS void* _handle = nullptr; // file mapping HANDLE #else int _fd = -1; // shm_open fd #endif }; #ifdef UTILS_WINDOWS // Quote an argument for the command line (file level: the definitions are indented too) _cold static std::string quote(const std::string& arg) { /* ... */ } #endif- In a header, the include guard is not a level for the C++ code:
#ifndef X_Hat column 0,#define X_H, the INCLUDE / DEFINE directives and their conditionals indented by 4 (#ifdef A+#include ...), while the namespace, structs, classes and their conditionals stay at column 0 (#ifdef A+struct ...). - A conditional never spans several sections or mixes indentation levels: close it and open one per section
(one
#ifdef UTILS_WINDOWSin DEFINE for the macros, another one in STRUCT for the structs, another one in TYPEDEF for the aliases) rather than one block whose content jumps between column 0 and 4. - A whole function that only exists on one platform: prefer one
#ifdefinside the body of each function (Unix / Windows implementations side by side) over one big file level block; a file that only builds on one platform is selected in the CMake (SRC_WINDOWS) instead of being wrapped in an#ifdef. - Multi-line macros (
\): the continuation lines follow their#define, indented one level more.
- In a header, the include guard is not a level for the C++ code:
Spacing
if (,for (,while (,switch (: space after the keyword; no space inside the parentheses.- Binary operators surrounded by spaces, no space for unary (
!x,++i,*it). for (const std::string& x: list),class A: public B,enum class E: std::size_t: no space before:.- Init list on its own line,
:at column 0:: _binary{binary}, _description{description}(an out-of-line constructor; an empty one defined in its class keeps it on its line, see below). &/*glued to the type:const std::string& name,char* buf,auto &[a, b]for structured bindings.template<typename T>without space.(void)for an empty parameter list, always.- One-liners: no space inside the braces and a
;after:{return this->_fd;};,{this->_help = false;};. - An empty constructor / destructor / operator defined in its class is one line, never a
{//* Nothing *//};block on several lines: its signature, its init list on the same line,{ /* Nothing */ };(a space inside the braces: a comment, not a statement), then its trailing comment; an operator that only returns:{return *this;};. The:of an init list on the line of its constructor is glued to the)(likeclass A: public B), never) ::HybridMemory(const std::size_t size, const MemoryMode mode = MemoryMode::Auto): HybridMemory(mode) {this->allocate_(size);}; // ...(xstyleruleCPP-INIT-COLON). The declarations keep their blank line between them (xstyleruleCPP-EMPTY-BODY, auto fix):
Not (the multi-line form):HybridMemory& operator=(HybridMemory&& other) noexcept {return *this;}; // take the memory and the handler of other // ---------- Constructor --------- // HybridMemory(const utils::system::MemoryMode mode = utils::system::MemoryMode::Auto): _requested{mode} { /* Nothing */ }; // select the backend HybridMemory(const std::size_t size, std::shared_ptr<utils::system::IGpu> gpu): _requested{utils::system::MemoryMode::Custom}, _gpu{gpu} { /* Nothing */ }; // a user handler HybridMemory(HybridMemory&& other) noexcept { /* Nothing */ }; // take the memory and the handler of other // ----------- Destructor --------- // ~HybridMemory() noexcept { /* Nothing */ }; // release the memoryHybridMemory(HybridMemory&& other) noexcept // take the memory and the handler of other { /* Nothing */ }; - Consecutive similar lines of one group share a column (overloads, the setters, the getters,
using,case):_hot _nodiscard bool hasAcceptOverload(void) const override {return false;}; _hot _nodiscard bool hasRecvOverload(void) const override {return false;}; - One-liner functions of a group are aligned tight: the
{of every body sits on the column right after the longest signature of the group + one space, never a wider fixed column:_cold _nodiscard bool hasWindow(void) const {return this->_window != nullptr;}; _cold _nodiscard rtype::engine::IWindow& getWindow(void) {return *this->_window;}; _cold _nodiscard rtype::engine::Layout& getRoot(void) {return this->_root;};- Every line of the group on that column: no line of the group left further right or left (a group whose setters sit on one column and two of its getters on another is wrong).
- A group is a run of consecutive lines of the same category (
/* setter */,/* getter */, the overloads of one name, oneenum'scases): a blank line or a/* label */starts a new column; the setters are never aligned on the getters. - Count it, never guess it: the column is the length of the longest signature (its indent included) + 1;
every other line gets exactly
column - its lengthspaces. A space too many or too few is wrong (two spaces before{on the longest line, a shorter line padded past the column, a group left on an old column after a line was added or renamed). xstyle checks it (CPP-ONELINER-ALIGN) and fixes it (--fix CPP-ONELINER-ALIGN). - Lengths far apart: levels. When the signatures of the lines to align fall in clearly separate lengths
(a jump of more than ~12 columns between them), align by level instead of one column for all: the short
ones together on their own tight column, the long ones together on theirs, the levels one after the other
(short first) with no blank line between them, even if that mixes setters and getters:
A level needs two lines or more: a single short (or long) one never stands alone, it joins the closest level and takes its column:_cold inline void setToggle(const bool toggle) {this->_toggle = toggle;}; _cold _nodiscard inline bool isToggle(void) const {return this->_toggle;}; _cold inline void setRepeat(const std::chrono::milliseconds delay) {this->_repeat = delay;}; _cold _nodiscard inline std::chrono::milliseconds getRepeat(void) const {return this->_repeat;};
Lengths close together (the usual_cold _nodiscard inline bool isToggle(void) const {return this->_toggle;}; _cold inline void setRepeat(const std::chrono::milliseconds delay) {this->_repeat = delay;}; _cold _nodiscard inline std::chrono::milliseconds getRepeat(void) const {return this->_repeat;};/* setter */and/* getter */groups): one column per group, as above. No space is ever "for later". - The trailing comment of a one-liner is glued: one space after
};, never a second column of comments:_cold inline void seed(const brain::IType seed) {this->_seed = seed;}; // seed of the random generator. Include comments keep their own alignment (seecpp-comments), this rule is only for functions.
- Trailing comments of members and declarations are glued to the code too (one space before
//, no column):brain::UIType _neuron = 0; // number of neuronsright understd::vector<brain::BrainNeuron> _neurons; // every neuron of the 2d space. - A function whose body is a single statement goes in the header, never in the .cpp: a definition that would
fit in 2 lines in the .cpp (signature, then
{return ...;}) is written as a one-liner in theFunctionblock of the.hpp, withinlineafter the attributes (not on avirtual/overridemethod, defined there withoutinline), and its declaration is removed from the Pre-Function block:
Same when editing / reviewing existing code: such a .cpp definition is moved to the header. It stays in the .cpp only when the header would need an include it doesn't have otherwise (cycle, heavy dependency)._hot _nodiscard inline std::size_t byteLength(void) const {return (this->bitLength() + 7) / 8;}; - Each declaration in its class block (
reference/layout.mdofcpp-class,xstyleruleCPP-CLASS-BLOCK):Pre-Function= declared only (body in the .cpp),Function= defined in the header ({...};, templates),Constructor/Destructor= theirs (never mixed), data members before the blocks. Moving a function from the .cpp to the header (or the other way) moves it betweenPre-FunctionandFunction.Operatoris free: an operator placed elsewhere is only worth a hint in a review, never a style error. - One empty line between functions and between logical blocks; never two.
Statements
this->on every member access (members and methods).- Short
if/else/loop with one statement: on the same line or on the next indented line without braces:
Several statements on one line inside braces are fine for tiny cases:if (safe_mode) lock.lock(); else (void)lock.try_lock(); for (const std::string& id: ids) this->removeUsage(id);{ids.push_back(fid); unknown = false; break;}. - Early return for trivial cases:
if (this->_finished.empty()) return;. - Loops:
- range-for first, with the explicit type (
for (const std::string& id: ids)), structured bindingsfor (const auto &[fid, flag]: this->_flags)(the only syntax possible) with_for unused parts; - index loops
for (std::size_t i = 0; i < n; ++i)(prefer++i,std::size_tfor indexes); while (true)+breakwith a comment per exit condition;do { ... } while (cond);when the first iteration is mandatory;- empty-body search loop is accepted:
for (index = 0; index < n && cond; ++index);.
- range-for first, with the explicit type (
switch: one line percasewithbreakaligned when short:switch (cb & 0b11) { case 0: event.button = utils::iomanip::MouseButton::Left; break; case 1: event.button = utils::iomanip::MouseButton::Middle; break; default: event.button = utils::iomanip::MouseButton::Unknown; break; }- Lambdas:
[&](const std::pair<std::string, bool>& p) {return p.first == id;}(explicit parameter types), captures listed explicitly when stored ([this, id, delay, fn](std::stop_token stoken) {). - Ternaries for short choices, parenthesized when nested.
- Discarded return values are cast:
(void)lock.try_lock();.
Includes
Always this order, groups one after the other (no empty line between them):
- the
#defineneeded by the personal libraries (the user's own libraries: libutils_Sectionlines...); - the personal libraries (
<utils/utils.hpp>,"..."or<...>); - the project headers in
"...", each one with the#defineit needs on the line just before it; - the external and standard libraries in
<...>, each one with the#defineit needs on the line just before it.
Inside each group: the longest name first, down to the shortest (name = what is between the quotes / angle
brackets, path included); between names of the same length, the most complex / specialized header first, the
simplest last. A #define stays glued above its include and moves with it.
#define _Attribute
#define _System
#include <utils/utils.hpp>
#include "engine/EngineType.hpp"
#include "engine/Entity.hpp"
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <unordered_map>
#include <memory>
#include <string>
- In a header: indented by 4 spaces (inside the guard), each include with an aligned trailing comment listing what
is used (
cpp-comments); in a .cpp: no comments. The project headers: relative path in a header ("../EngineType.hpp"), path frominclude/in a .cpp (cpp-class). - Inside a personal library itself (libutils), its own headers are project headers (group 3).
- Only what the file uses; an include that becomes unused is removed.
Types & C++ usage
- Fully qualified names, never
using namespace(std::size_t,utils::exception::ErrorException). - No
auto: always write the type, even when it is long. Allowed only for an iterator (auto it = this->_tasks.find(id);), the structured bindings (const auto &[a, b], mandatory syntax), or when the user explicitly asks for it. - No
usingexcept to name a custom type of the project (using Payloads = std::vector<utils::network::Payload>;,using ParsedUsages = ...;, migration aliases), or when the user explicitly asks for it. In a header, everyusing/typedefalias goes in a/* TYPEDEF */section and everystruct/union(forward declarations included) in a/* STRUCT */section (cpp-classreference/layout.md). Neverusing std::...;, never ausingto shorten a standard type in the code. consteverywhere it applies: by-value parameters too (const bool safe_mode,const std::size_t i),const&for objects,constmethods,mutablefor the mutex.- Default values at the declaration (
int _fd = -1;,std::string _description = "...";),"[None]"as default text. nullptr(neverNULL),static_cast(never C casts except(void)),std::size_tfor sizes.- Modern C++20:
contains,starts_with,std::erase,std::jthread+std::stop_token, structured bindings,if constexpr,static_assert+ type traits / concepts,std::optional,enum class. - Return
std::optional<std::string>from check hooks:std::nullopt= valid, the string = error message. - Templates with a
boolnon-type parameter for behavior switches:template<bool force = false>. noexceptonclose, destructors and functions that must not throw.final/overrideon every override.- Locks:
std::lock_guard lock(this->_lock);,std::unique_lock<std::mutex> lock(this->_lock, std::defer_lock);. - Rule of five explicit (
= default/= delete), copy/move deleted by default.
Errors
- With libutils:
throw utils::exception::ErrorException(utils::exception::InternalCode::X, "info");(FatalExceptionunrecoverable,WarningException(...).formated()printed onstd::cerrfor warnings,failsafeparameter to switch between warning and throw). - Without libutils: standard exceptions (
std::runtime_error,std::invalid_argument...) or the project ones. - Re-throw hook/callback errors wrapped with context:
catch (const std::exception& e) {throw utils::exception::ErrorException(InternalCode::ArgParserHook, e.what());}.
Attributes
Every attribute / alignment / hint goes through the libutils macros when the project uses libutils
(cpp-class/scripts/detect_libutils.sh), alignment included:
_alignas(std::hardware_destructive_interference_size) std::atomic<std::size_t> _head = 0;, never a bare
alignas(...) (<utils/utils.hpp> also guarantees std::hardware_*_interference_size, fallback 64).
Lookup order before writing any attribute:
- the libutils default macros (table below,
libutils/reference/api/attribute.md); - not there: the attribute files really used, hard imported in the project or installed on the system
(
bash cpp-class/scripts/list_attributes.sh <project_root>,cpp-class= that skill folder, lists every#define _x), a newer libutils may have it; - still not there (or no libutils): the standard form,
[[...]]([[gnu::...]]),alignas(...), or__attribute__((...))/__builtin_*when no standard spelling exists.
| libutils | standard |
|---|---|
_hot / _cold | [[gnu::hot]] / [[gnu::cold]] |
_nodiscard | [[nodiscard]] |
_unused | [[maybe_unused]] |
_likely / _unlikely | [[likely]] / [[unlikely]] |
_fallthrough | [[fallthrough]] |
_noinline | [[noinline]] ([[gnu::noinline]] for gcc) |
_deprecated(info) | [[deprecated(info)]] |
_noaddress / _packed | [[no_unique_address]] / [[gnu::packed]] |
_assume(expr) | [[assume(expr)]] |
_alignas(n) | alignas(n) (n often std::hardware_destructive_interference_size) |
_hidden | [[gnu::visibility("hidden")]] |
_ctor / _dtor | [[gnu::constructor]] / [[gnu::destructor]] |
_likely_c(c) / _unlikely_c(c) / _expect(c, v) | __builtin_expect(!!(c), 1) / (!!(c), 0) / (c, v) |
_alloc_size(i) / _alloc_size_mul(i, j) | [[gnu::alloc_size(i)]] / [[gnu::alloc_size(i, j)]] |
_read_only(p, s) / _write_only(p, s) | [[gnu::access(read_only, p, s)]] / [[gnu::access(write_only, p, s)]] |
_nonnull(p) | [[gnu::nonnull(p)]] |
_legacy / _migration(x, y, z) | [[deprecated("...")]] |
- Placement: before the return type (
_cold _nodiscard int getFd(void) const),_likely/_unlikelyafter the condition (if (id == 0) _unlikely {,} else _likely {),_unusedbefore the parameter type. _hoton hot paths (alloc, send, parse, compute),_coldon setup/setters/getters/cancel,_nodiscardon every getter and function whose result matters.
Checking
xstyle (TsukiNi22/xstyle, installed by curl -fsSL https://tsukini22.github.io/my-universe/install.sh | bash -s then sudo dnf|apt|pacman install xstyle (packages of my-universe, sources: TsukiNi22/xstyle; no curl: wget -qO- instead of curl -fsSL)) checks this style,
cpp-comments / cpp-class layout points and the libutils usage (LU-* rules), with a severity per rule and the fix
proposed. When it is installed (command -v xstyle), run it on the files written or reviewed and fix what it
reports: xstyle --rtk <files|dirs> -r, xstyle --rtk --fix [CODES] <paths> (preview with -n), xstyle -x CODE explains a
rule, // xstyle: ignore CODE for a justified exception. Its findings are heuristic: a rule that contradicts the
local style of the file loses (local style wins).
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation | Stars: 318k | Updated | Claude CodeCodex | Unverified | Install |
| requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirements | Stars: 318k | Updated | Claude CodeCodex | Unverified | Install |
| using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback | Stars: 318k | Updated | Claude CodeCodex | Unverified | Install |
| verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always | Stars: 318k | Updated | Claude CodeCodex | Unverified | Install |