C++ 最佳实践
现代 C++ 编码规范、const 正确性、避免裸指针、RAII 原则
C++ 最佳实践
C++ 给了你巨大的能力,也给了你巨大的犯错空间。好的习惯让 C++ 代码安全、现代、可维护。
学完本章你将: 掌握现代 C++ 编码规范、const 正确性、避免裸指针、RAII 原则。
编码规范速查
cpp
// ✅ 现代 C++ 推荐风格
#include <iostream>
#include <memory>
#include <string>
#include <vector>
// 类型命名:PascalCase
class StudentManager { };
// 函数命名:camelCase
auto findByName(const std::string &name) -> std::vector<Student>;
// 变量命名:snake_case
int max_students = 30;
// 避免 using namespace std;(尤其在头文件)
using std::string; // 合理:只引入需要的
const 三原则
cpp
// 1. const 变量——防止意外修改
const int MAX = 100;
// 2. const 引用参数——高效且不可修改
void print(const std::string &s);
// 3. const 成员函数——承诺不修改对象状态
class Point {
int x, y;
public:
int getX() const { return x; } // const 正确性
};
现代 C++ 铁律
cpp
// 1. 不用裸 new/delete
auto p = std::make_unique<int>(42); // ✅
// int *p = new int(42); delete p; // ❌
// 2. 用容器不用 C 数组
std::vector<int> v = {1, 2, 3}; // ✅
// int arr[3] = {1, 2, 3}; // ❌
// 3. 用 string 不用 char*
std::string name = "小明"; // ✅
// char *name = "小明"; // ❌
// 4. 用 nullptr 不用 NULL
int *p = nullptr; // ✅
// int *p = NULL; // ❌
// 5. 用 algorithm + lambda,不用手写循环
std::find_if(v.begin(), v.end(), // ✅
[](int x) { return x > 5; });
// for (...) if (...) break; // ❌
RAII 原则
cpp
// 所有资源都应封装在类中:
// - 构造函数获取资源
// - 析构函数释放资源
// - 拷贝控制(或 disable)正确处理
// 标准库已经实现了大部分:
// unique_ptr, shared_ptr → 内存
// lock_guard, unique_lock → 互斥锁
// fstream → 文件
// vector, string → 动态缓冲区