1. 遵循代码简洁原则
尽量避免冗余代码,通过模块化设计、清晰的命名和良好的结构,让代码更易于阅读和维护
2. 优先使用智能指针
使用 std::unique_ptr 和 std::shared_ptr 替代裸指针来管理动态内存,以减少内存泄漏风险。
#include <memory>
std::unique_ptr<int> ptr = std::make_unique<int>(42); // 自动管理内存
3. 使用范围 for 循环
通过范围 for 循环提高代码的简洁性和可读性。
#include <vector>
std::vector<int> nums = {1, 2, 3};
for (int num : nums) {
std::cout << num << std::endl;
}
4. 避免魔法数字
避免在代码中使用硬编码的数字或字符串,改用常量或枚举来代替。
constexpr int MaxRetries = 3;
for (int i = 0; i < MaxRetries; ++i) {
// 重试逻辑
}
5. 优先使用标准库
尽量使用 STL 容器(如 std::vector、std::map)和算法(如 std::sort),而不是手动实现这些功能。
#include <vector>
#include <algorithm>
std::vector<int> vec = {3, 1, 2};
std::sort(vec.begin(), vec.end());
6. 使用 constexpr优化性能
通过 constexpr 在编译期间计算结果,降低运行时的开销。
constexpr int factorial(int n) {
return (n <= 1) ? 1 : n * factorial(n - 1);
}
7. 使用 RAII 管理资源
通过 RAII(Resource Acquisition Is Initialization)确保资源的分配与释放与对象生命周期绑定。
#include <fstream>
void processFile() {
std::ifstream file("data.txt"); // 构造时打开文件,析构时关闭文件
if (!file) {
throw std::runtime_error("文件无法打开");
}
}
8. 避免 using namespace std
using namespace std; 容易造成命名冲突,尤其是在大型项目中,推荐明确使用命名空间。
std::vector<int> nums = {1, 2, 3}; // 使用 std
9. 线程安全
在多线程环境中,使用同步工具(如 std::mutex)确保共享数据的一致性。
#include <mutex>
std::mutex mtx;
void safeFunction() {
std::lock_guard<std::mutex> lock(mtx);
// 线程安全的代码
}
10. 使用 noexcept 优化函数
明确标记不会抛出异常的函数为 noexcept,提高性能和可靠性。
void safeFunction() noexcept {
// 安全代码
}
11. 防止隐式转换
使用 explicit 防止构造函数进行意外的隐式类型转换。
class MyClass {
public:
explicit MyClass(int value);
};
12. 使用 SFINAE 和概念约束
通过 SFINAE 和 C++20 的概念限制模板参数,提高代码的灵活性和类型安全性。
#include <concepts>
template <std::integral T>
T add(T a, T b) {
return a + b;
}
13. 范围锁
使用 std::scoped_lock 一次锁定多个资源,避免死锁。
#include <mutex>
std::mutex mtx1, mtx2;
void safeOperation() {
std::scoped_lock lock(mtx1, mtx2); // 同时锁定多个锁
// 安全操作
}
14. 遵循 Rule of Zero、Three 和 Five
对于资源管理:
- Rule of Zero:避免手动管理资源。
- Rule of Three:需要定义析构函数时,通常还需要定义拷贝构造和拷贝赋值运算符。
- Rule of Five:进一步定义移动构造和移动赋值运算符。
15. 注释与文档
确保代码有清晰的注释,并使用工具(如 Doxygen)生成开发文档。
/// 获取圆的面积
/// @param radius 半径
/// @return 圆的面积
double getCircleArea(double radius);
16. 单元测试
通过 Google Test 或 Catch2 等工具编写单元测试,提高代码质量。
17. 启用编译器警告
使用编译器选项(如 -Wall -Wextra)开启警告,并将警告处理为错误(如 -Werror)。