Skip to content

code_style

zhaoxi edited this page Aug 31, 2024 · 1 revision

编码规范

注意

本文档待完善

格式化要求

采用 .clang-format 的要求进行代码格式化

字面量

在使用字面量的时候,尽量避免隐式转换,必要时可使用用户定义字面量,例如

double val = 42.0;
float val2 = 42.f;
uint32_t val3 = 42u;

using namespace std::string_literals;

"Hello, World!"s;

初始化

使用 C++11 起的直接列表初始化,或花括号包围的值初始化对变量进行初始化操作,例如

int test_a{1};
bool test_b{};

如果类型名过长,建议使用 auto 关键字进行类型推导,例如

auto vec = std::vector{1, 2, 3, 4, 5};
auto it = vec.begin();
auto p = std::make_unique<int>(42);

当使用返回值为聚合类型的函数进行初始化变量时,建议使用结构化绑定,例如

auto get() { return std::make_tuple{1, 3.14, "ABC"s, true}; }
auto [a, b, c, d] = get();

语句

一行只写一条语句,不要在一行中写多条语句

using namespace 禁止在头文件中使用,最多在源文件中使用

循环语句

使用 for 循环时,尽量使用 range-based for,例如

std::vector vec{1, 2, 3, 4, 5};
for (const auto& i : vec)
    std::println("{}", i);

标识符命名

严格按照 cppreference 中的要求进行标识符命名

全局函数、成员函数名使用小驼峰命名法,例如

void myFunction();

除了部分硬编码要求可以使用其他格式的命名法,例如

class Promise
{
    int _retval{};

public:
    std::suspend_always initial_suspend() { return {}; }
    std::suspend_always final_suspend() noexcept { return {}; }
    void unhandled_exception() { throw; }

    std::suspend_always yield_value(int ret)
    {
        _retval = ret;
        return {};
    }

    void return_void() { _retval = 0; }

    std::coroutine_handle<Promise> get_return_object()
    {
        return std::coroutine_handle<Promise>::from_promise(*this);
    }

    int getValue() { return _retval; }
};

class Task
{
public:
    using promise_type = Promise;

private:
    std::coroutine_handle<promise_type> _coro;

public:
    Task(std::coroutine_handle<promise_type> coro) : _coro(coro) {}
};

全局变量、成员变量名使用蛇形命名法,如 int my_variable{};

类名采用大驼峰命名法,如 class MyClass

枚举类型名使用大驼峰命名法,如

enum class MyEnum {};

枚举值使用大写字母和下划线,如

enum class MyEnum
{
    MY_VALUE = 42,
    MY_OTHER_VALUE = 43
};

模板参数名使用大驼峰命名法,如 template <typename MyType>

命名空间使用蛇形命名法,如 namespace my_ns

文件名使用蛇形命名法,如 my_file.cpp

Clone this wiki locally