1. C++模块化编程核心概念解析
模块化编程是把一个大型程序分解为多个独立功能单元的开发方法。在C++中,这通常通过头文件(.h/.hpp)和源文件(.cpp)的组合来实现。现代C++17/20标准进一步引入了正式的模块(module)特性,但本文主要讨论传统的实现方式。
模块化的本质是"分而治之":每个模块应当具有单一职责,对外暴露清晰的接口,隐藏实现细节。好的模块划分能让代码像乐高积木一样灵活组合。我在处理超过10万行代码的金融交易系统时,模块化使团队协作效率提升了3倍以上。
关键认知:模块化不是简单的文件分割,而是基于功能内聚性和接口设计的系统工程
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 模块化实现的技术要素
2.1 头文件设计规范
头文件是模块的"说明书",需要严格遵循以下原则:
- 使用
#pragma once或传统的#ifndef守卫防止重复包含 - 只包含必要的其他头文件(前向声明优于直接包含)
- 接口函数必须添加详细注释(参数说明、返回值、异常情况)
- 模板实现通常需要直接放在头文件中
cpp复制// 示例:安全的头文件结构
#pragma once
#include <vector> // 必须的STL依赖
// 前向声明替代不必要的包含
class OtherClass;
namespace MyModule {
class Processor {
public:
explicit Processor(int init_param);
// 处理数据的线程安全方法
std::vector<float> process(const std::vector<float>& input);
private:
int internal_state_;
};
}
2.2 源文件实现要点
对应的.cpp文件需要:
- 包含所属模块的头文件(自包含原则)
- 实现所有声明的方法
- 可以包含仅内部使用的辅助函数
- 使用匿名namespace封装模块私有实现
cpp复制#include "processor.h"
#include <algorithm> // 仅在实现需要的头文件
namespace {
// 模块内部使用的辅助函数
float normalizeValue(float v) {
return std::clamp(v, 0.0f, 1.0f);
}
}
namespace MyModule {
Processor::Processor(int init_param)
: internal_state_(init_param) {}
std::vector<float> Processor::process(const std::vector<float>& input) {
std::vector<float> output;
for (auto val : input) {
output.push_back(normalizeValue(val * internal_state_));
}
return output;
}
}
3. 模块依赖管理实践
3.1 物理目录结构设计
推荐的项目布局示例:
code复制project_root/
├── include/ # 对外公开的头文件
│ └── MyLib/
│ ├── module1.h
│ └── module2.h
├── src/ # 实现文件
│ ├── module1.cpp
│ └── module2.cpp
├── tests/ # 单元测试
└── third_party/ # 第三方依赖
3.2 依赖控制技巧
- 避免循环依赖:使用接口类或回调机制解耦
- 减少编译依赖:Pimpl惯用法示例:
cpp复制// widget.h
class Widget {
public:
Widget();
~Widget();
void doSomething();
private:
struct Impl;
std::unique_ptr<Impl> pImpl;
};
// widget.cpp
struct Widget::Impl {
// 实际实现细节
void realWork() { /*...*/ }
};
Widget::Widget() : pImpl(std::make_unique<Impl>()) {}
Widget::~Widget() = default;
void Widget::doSomething() { pImpl->realWork(); }
4. 构建系统集成方案
4.1 CMake最佳实践
现代CMake的模块化配置示例:
cmake复制# 声明模块库
add_library(MyModule STATIC
src/module1.cpp
src/module2.cpp
)
# 精确控制头文件可见性
target_include_directories(MyModule PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
# 定义依赖关系
target_link_libraries(MyModule PUBLIC
Threads::Threads
Boost::filesystem
)
4.2 跨平台注意事项
- Windows下需要显式导出符号:
cpp复制#ifdef MYMODULE_EXPORTS
#define API __declspec(dllexport)
#else
#define API __declspec(dllimport)
#endif
class API MyExportedClass { /*...*/ };
- Linux/Unix下注意符号可见性:
bash复制# 编译时添加-fvisibility=hidden
5. 模块化调试与测试策略
5.1 单元测试框架集成
使用Catch2的测试模块示例:
cpp复制#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include "../src/math_utils.h"
TEST_CASE("Vector normalization") {
MathUtils utils;
auto result = utils.normalize({1.0f, 2.0f, 3.0f});
REQUIRE(result.size() == 3);
REQUIRE_THAT(result[0], Catch::Matchers::WithinAbs(0.27f, 0.01f));
}
5.2 性能分析技巧
- 使用Google Benchmark测量模块性能:
cpp复制#include <benchmark/benchmark.h>
static void BM_ModuleProcess(benchmark::State& state) {
Processor p(42);
std::vector<float> data(1000, 1.5f);
for (auto _ : state) {
benchmark::DoNotOptimize(p.process(data));
}
}
BENCHMARK(BM_ModuleProcess);
- 使用perf工具分析热点函数:
bash复制perf record -g ./my_program
perf report -n --stdio
6. 现代C++模块化新特性
6.1 C++20 Modules实践
虽然尚未被所有编译器完全支持,但可以开始尝试:
cpp复制// math_module.ixx
export module Math;
export namespace Math {
int add(int a, int b) { return a + b; }
}
// main.cpp
import Math;
int main() {
return Math::add(2, 3);
}
6.2 编译期模块化
利用constexpr和模板元编程:
cpp复制template <typename T>
constexpr auto TypeInfo = "Unknown";
template <>
constexpr auto TypeInfo<int> = "Integer";
// 使用时作为编译期字符串
static_assert(TypeInfo<int> == "Integer");
7. 大型项目模块化案例
7.1 插件系统架构
动态加载模块的通用模式:
cpp复制// 定义插件接口
class IPlugin {
public:
virtual ~IPlugin() = default;
virtual void execute() = 0;
};
// 加载插件
void loadPlugin(const std::string& path) {
auto handle = dlopen(path.c_str(), RTLD_LAZY);
auto create = reinterpret_cast<IPlugin*(*)()>(dlsym(handle, "createPlugin"));
std::unique_ptr<IPlugin> plugin(create());
plugin->execute();
}
7.2 微服务通信模块
使用Protobuf定义接口:
protobuf复制syntax = "proto3";
message DataRequest {
repeated float inputs = 1;
}
message DataResponse {
repeated float outputs = 1;
}
service DataProcessor {
rpc Process (DataRequest) returns (DataResponse);
}
8. 性能优化专项
8.1 内存局部性优化
调整数据结构提高缓存命中率:
cpp复制// 不好的做法:分散的内存访问
struct Particle {
Vec3 position;
// 40字节其他字段...
float velocity;
};
// 优化后:SoA布局
struct Particles {
std::vector<Vec3> positions;
std::vector<float> velocities;
};
8.2 并行处理模式
使用TBB实现模块并行化:
cpp复制#include <tbb/parallel_for.h>
void processAll(std::vector<Data>& dataset) {
tbb::parallel_for(tbb::blocked_range<size_t>(0, dataset.size()),
[&](auto range) {
for (size_t i = range.begin(); i != range.end(); ++i) {
dataset[i].process();
}
});
}
9. 安全编程实践
9.1 接口安全设计
- 使用强类型替代原始类型:
cpp复制class UserId {
int id_;
public:
explicit UserId(int id) : id_(id) {}
operator int() const { return id_; }
};
void deleteUser(UserId id); // 比deleteUser(int id)更安全
- 资源管理遵循RAII原则:
cpp复制class FileHandle {
FILE* file_;
public:
explicit FileHandle(const char* path) : file_(fopen(path, "r")) {
if (!file_) throw std::runtime_error("Open failed");
}
~FileHandle() { if (file_) fclose(file_); }
// 禁用拷贝
FileHandle(const FileHandle&) = delete;
FileHandle& operator=(const FileHandle&) = delete;
// 允许移动
FileHandle(FileHandle&& other) noexcept : file_(other.file_) {
other.file_ = nullptr;
}
};
10. 工具链配置指南
10.1 VSCode开发环境
配置tasks.json示例:
json复制{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "cmake --build ${workspaceFolder}/build",
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": ["$gcc"]
}
]
}
10.2 静态分析集成
使用clang-tidy的CMake配置:
cmake复制# 启用静态分析
set(CMAKE_CXX_CLANG_TIDY
clang-tidy;
-checks=*,-modernize-use-trailing-return-type
)
11. 跨语言交互方案
11.1 Python扩展模块
使用pybind11创建Python绑定:
cpp复制#include <pybind11/pybind11.h>
int add(int a, int b) { return a + b; }
PYBIND11_MODULE(example, m) {
m.def("add", &add, "A function that adds two numbers");
}
11.2 WebAssembly编译
使用Emscripten编译为WASM:
bash复制emcc -O3 -s WASM=1 -s EXPORTED_FUNCTIONS="['_processData']" \
-o module.js module.cpp
12. 持续集成实践
12.1 GitHub Actions配置
自动化构建测试示例:
yaml复制name: CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: |
sudo apt-get install -y cmake g++
mkdir build && cd build
cmake .. && make
ctest --output-on-failure
13. 性能关键模块优化
13.1 SIMD指令应用
使用编译器内置函数:
cpp复制#include <immintrin.h>
void vectorAdd(const float* a, const float* b, float* c, size_t n) {
for (size_t i = 0; i < n; i += 8) {
__m256 va = _mm256_load_ps(a + i);
__m256 vb = _mm256_load_ps(b + i);
__m256 vc = _mm256_add_ps(va, vb);
_mm256_store_ps(c + i, vc);
}
}
13.2 内存池实现
定制分配器示例:
cpp复制class MemoryPool {
struct Block { Block* next; };
Block* freeList = nullptr;
public:
void* allocate(size_t size) {
if (!freeList) {
return ::operator new(size);
}
auto block = freeList;
freeList = freeList->next;
return block;
}
void deallocate(void* ptr, size_t) {
auto block = static_cast<Block*>(ptr);
block->next = freeList;
freeList = block;
}
};
14. 设计模式应用
14.1 工厂方法模式
模块化对象创建:
cpp复制class ISerializer {
public:
virtual std::string serialize(const Document&) = 0;
virtual ~ISerializer() = default;
};
class JsonSerializer : public ISerializer { /*...*/ };
class XmlSerializer : public ISerializer { /*...*/ };
std::unique_ptr<ISerializer> createSerializer(const std::string& format) {
if (format == "json") return std::make_unique<JsonSerializer>();
if (format == "xml") return std::make_unique<XmlSerializer>();
throw std::runtime_error("Unsupported format");
}
14.2 观察者模式实现
事件通知系统:
cpp复制class Observer {
public:
virtual void update(const Event&) = 0;
};
class Subject {
std::vector<Observer*> observers_;
public:
void attach(Observer* o) { observers_.push_back(o); }
void notify(const Event& e) {
for (auto o : observers_) o->update(e);
}
};
15. 代码生成技术
15.1 元编程代码生成
使用模板生成特化代码:
cpp复制template <typename T>
struct TypeTraits;
template <>
struct TypeTraits<int> {
static constexpr const char* name = "int";
static constexpr size_t size = sizeof(int);
};
// 使用时
auto name = TypeTraits<decltype(var)>::name;
15.2 外部工具集成
使用Python脚本生成C++代码:
python复制def generate_enum(name, values):
print(f"enum class {name} {{")
for v in values:
print(f" {v},")
print("};")
generate_enum("Color", ["Red", "Green", "Blue"])
16. 异常安全设计
16.1 强异常保证实现
使用copy-and-swap惯用法:
cpp复制class ResourceHolder {
Resource* res;
void swap(ResourceHolder& other) noexcept {
std::swap(res, other.res);
}
public:
ResourceHolder(const ResourceHolder& other) : res(new Resource(*other.res)) {}
ResourceHolder& operator=(ResourceHolder other) noexcept {
swap(other);
return *this;
}
~ResourceHolder() { delete res; }
};
16.2 错误处理策略
使用expected替代异常:
cpp复制template <typename T, typename E>
class Expected {
union { T value; E error; };
bool has_value;
public:
Expected(T v) : value(v), has_value(true) {}
Expected(E e) : error(e), has_value(false) {}
bool valid() const { return has_value; }
T get() const { if (!has_value) throw ...; return value; }
E error() const { if (has_value) throw ...; return error; }
};
17. 模板元编程技巧
17.1 SFINAE应用示例
类型特征检测:
cpp复制template <typename T>
auto serialize(const T& obj) -> decltype(obj.serialize(), std::string()) {
return obj.serialize();
}
template <typename T>
auto serialize(const T& obj) -> decltype(to_string(obj), std::string()) {
return to_string(obj);
}
17.2 编译期字符串处理
使用constexpr字符串操作:
cpp复制constexpr size_t strlen(const char* s) {
size_t len = 0;
while (s[len] != '\0') ++len;
return len;
}
static_assert(strlen("hello") == 5);
18. 并发编程模式
18.1 线程安全队列
使用条件变量实现:
cpp复制template <typename T>
class ConcurrentQueue {
std::queue<T> queue_;
std::mutex mtx_;
std::condition_variable cv_;
public:
void push(T item) {
std::lock_guard lock(mtx_);
queue_.push(std::move(item));
cv_.notify_one();
}
T pop() {
std::unique_lock lock(mtx_);
cv_.wait(lock, [this]{ return !queue_.empty(); });
T item = std::move(queue_.front());
queue_.pop();
return item;
}
};
18.2 无锁编程示例
原子操作应用:
cpp复制class AtomicCounter {
std::atomic<int> count_{0};
public:
void increment() {
count_.fetch_add(1, std::memory_order_relaxed);
}
int get() const {
return count_.load(std::memory_order_acquire);
}
};
19. 内存模型深入
19.1 内存序理解
不同memory_order的使用场景:
cpp复制std::atomic<bool> ready{false};
int data = 0;
// 线程1
data = 42;
ready.store(true, std::memory_order_release);
// 线程2
while (!ready.load(std::memory_order_acquire));
assert(data == 42); // 保证成立
19.2 缓存一致性
伪共享问题解决:
cpp复制struct alignas(64) CacheLineAligned {
int value1; // 独占一个缓存行
};
static_assert(sizeof(CacheLineAligned) == 64);
20. 模块化设计模式
20.1 策略模式应用
运行时算法选择:
cpp复制class SortStrategy {
public:
virtual void sort(std::vector<int>&) = 0;
};
class QuickSort : public SortStrategy { /*...*/ };
class MergeSort : public SortStrategy { /*...*/ };
class Sorter {
std::unique_ptr<SortStrategy> strategy_;
public:
void setStrategy(std::unique_ptr<SortStrategy> s) {
strategy_ = std::move(s);
}
void sort(std::vector<int>& data) {
strategy_->sort(data);
}
};
20.2 装饰器模式
动态添加功能:
cpp复制class Stream {
public:
virtual void write(const std::string&) = 0;
};
class FileStream : public Stream { /*...*/ };
class BufferedStream : public Stream {
Stream* stream_;
public:
explicit BufferedStream(Stream* s) : stream_(s) {}
void write(const std::string& data) override {
// 添加缓冲逻辑
stream_->write(data);
}
};
21. 代码质量保障
21.1 静态分析集成
使用clang-format统一风格:
.clang-format示例:
code复制BasedOnStyle: Google
IndentWidth: 4
ColumnLimit: 100
AllowShortFunctionsOnASingleLine: All
21.2 单元测试覆盖率
使用gcov生成报告:
bash复制g++ --coverage -O0 -g test.cpp -o test
./test
gcov -r test.cpp
22. 性能剖析方法
22.1 微基准测试
使用Google Benchmark比较算法:
cpp复制static void BM_StdSort(benchmark::State& state) {
std::vector<int> data(state.range(0));
for (auto _ : state) {
std::sort(data.begin(), data.end());
}
}
BENCHMARK(BM_StdSort)->Range(8, 8<<10);
22.2 热点分析
使用perf定位瓶颈:
bash复制perf record -F 999 -g -- ./my_program
perf report -g 'graph,0.5,caller'
23. 多语言交互
23.1 C接口设计
兼容C的接口示例:
cpp复制extern "C" {
struct CHandle;
CHandle* create_processor(int param);
void process_data(CHandle*, const float* in, float* out, size_t n);
void destroy_processor(CHandle*);
}
23.2 FFI集成
Rust调用C++示例:
rust复制#[link(name = "mylib", kind = "static")]
extern "C" {
fn create_processor(param: i32) -> *mut std::ffi::c_void;
fn process_data(handle: *mut std::ffi::c_void, input: *const f32, output: *mut f32, len: usize);
}
24. 编译器特性利用
24.1 属性语法应用
使用GNU扩展:
cpp复制[[gnu::always_inline]] inline void criticalFunc() {
// 强制内联
}
__attribute__((section(".secure"))) void secureFunc() {
// 放入特定段
}
24.2 编译期优化
使用likely/unlikely提示分支预测:
cpp复制if (__builtin_expect(ptr != nullptr, 1)) {
// 很可能执行的路径
} else {
// 不太可能的分支
}
25. 调试技巧进阶
25.1 条件断点设置
GDB高级用法:
bash复制# 当size>100时中断
break foo.cpp:123 if size > 100
# 打印复杂结构
set print pretty on
p *myObject
25.2 内存调试工具
使用AddressSanitizer检测内存错误:
bash复制clang++ -fsanitize=address -g program.cpp
./a.out # 自动检测内存问题
26. 跨平台开发
26.1 系统API抽象
统一文件操作接口:
cpp复制class File {
#ifdef _WIN32
HANDLE handle_;
#else
int fd_;
#endif
public:
bool open(const char* path);
size_t read(void* buf, size_t len);
// ...
};
26.2 字节序处理
网络序转换:
cpp复制inline uint64_t htonll(uint64_t host) {
#ifdef BIG_ENDIAN
return host;
#else
return ((uint64_t)htonl(host & 0xFFFFFFFF) << 32) | htonl(host >> 32);
#endif
}
27. 嵌入式开发专项
27.1 寄存器操作
安全访问硬件寄存器:
cpp复制volatile uint32_t* const GPIOA = reinterpret_cast<uint32_t*>(0x40020000);
void setPin(uint8_t pin) {
*GPIOA |= (1 << pin); // 原子操作
}
27.2 内存受限优化
使用位域节省空间:
cpp复制struct SensorData {
uint32_t temp : 10; // 10位存储温度
uint32_t humi : 10; // 10位存储湿度
uint32_t status : 4; // 4位状态标志
};
static_assert(sizeof(SensorData) == 4);
28. 图形编程模块
28.1 OpenGL封装
现代C++风格封装:
cpp复制class Texture {
GLuint id_;
public:
Texture() { glGenTextures(1, &id_); }
~Texture() { glDeleteTextures(1, &id_); }
void bind(GLenum target) const {
glBindTexture(target, id_);
}
};
28.2 Vulkan初始化
模块化设备管理:
cpp复制class VulkanDevice {
VkDevice device_;
VkQueue graphicsQueue_;
public:
explicit VulkanDevice(const PhysicalDevice& pdev) {
float queuePriority = 1.0f;
VkDeviceQueueCreateInfo queueInfo{};
queueInfo.queueFamilyIndex = pdev.findQueueFamily();
queueInfo.queueCount = 1;
queueInfo.pQueuePriorities = &queuePriority;
VkDeviceCreateInfo createInfo{};
createInfo.queueCreateInfoCount = 1;
createInfo.pQueueCreateInfos = &queueInfo;
vkCreateDevice(pdev.handle(), &createInfo, nullptr, &device_);
vkGetDeviceQueue(device_, queueInfo.queueFamilyIndex, 0, &graphicsQueue_);
}
};
29. 网络编程模块
29.1 异步IO设计
使用io_uring实现:
cpp复制class UringSocket {
int fd_;
io_uring ring_;
public:
void asyncRead(void* buf, size_t len, Callback cb) {
auto* sqe = io_uring_get_sqe(&ring_);
io_uring_prep_read(sqe, fd_, buf, len, 0);
io_uring_sqe_set_data(sqe, new Callback(std::move(cb)));
io_uring_submit(&ring_);
}
void pollEvents() {
io_uring_cqe* cqe;
if (io_uring_peek_cqe(&ring_, &cqe) == 0) {
auto* cb = static_cast<Callback*>(io_uring_cqe_get_data(cqe));
(*cb)(cqe->res);
delete cb;
io_uring_cqe_seen(&ring_, cqe);
}
}
};
29.2 协议解析器
模块化协议处理:
cpp复制class ProtocolParser {
public:
virtual ~ProtocolParser() = default;
virtual size_t parse(const uint8_t* data, size_t len) = 0;
};
class HttpParser : public ProtocolParser { /*...*/ };
class MqttParser : public ProtocolParser { /*...*/ };
30. 脚本扩展支持
30.1 Lua绑定
使用sol2库集成Lua:
cpp复制lua["game"] = sol::new_table();
lua["game"]["player"] = Player();
lua.script(R"(
function update(dt)
game.player:move(dt * 10)
end
)");
30.2 脚本热重载
动态加载机制:
cpp复制void reloadScript(const std::string& path) {
static std::unordered_map<std::string, fs::file_time_type> lastWriteTimes;
auto currentWrite = fs::last_write_time(path);
if (lastWriteTimes[path] != currentWrite) {
loadScript(path); // 重新加载
lastWriteTimes[path] = currentWrite;
}
}
31. 数学库设计
31.1 SIMD向量运算
使用编译器内置函数:
cpp复制struct Vec4 {
__m128 data;
Vec4 operator+(const Vec4& other) const {
return {_mm_add_ps(data, other.data)};
}
float dot(const Vec4& other) const {
__m128 dp = _mm_dp_ps(data, other.data, 0xF1);
return _mm_cvtss_f32(dp);
}
};
31.2 矩阵优化
行主序存储优化:
cpp复制class Matrix4x4 {
alignas(16) float data[16]; // 行主序
Matrix4x4 operator*(const Matrix4x4& other) const {
Matrix4x4 result;
for (int i = 0; i < 4; ++i) {
__m128 row = _mm_load_ps(&data[i*4]);
for (int j = 0; j < 4; ++j) {
__m128 col = _mm_load_ps(&other.data[j]);
result.data[i*4 + j] = _mm_cvtss_f32(
_mm_dp_ps(row, col, 0xF1));
}
}
return result;
}
};
32. 序列化方案
32.1 二进制序列化
类型安全实现:
cpp复制template <typename T>
void serialize(const T& obj, std::ostream& out) {
static_assert(std::is_trivially_copyable_v<T>,
"Type must be trivially copyable");
out.write(reinterpret_cast<const char*>(&obj), sizeof(obj));
}
template <typename T>
T deserialize(std::istream& in) {
T obj;
in.read(reinterpret_cast<char*>(&obj), sizeof(obj));
return obj;
}
32.2 文本格式处理
JSON序列化示例:
cpp复制class JsonSerializer {
public:
std::string serialize(const Document& doc) {
rapidjson::Document json;
json.SetObject();
json.AddMember("id", doc.id(), json.GetAllocator());
// ...
rapidjson::StringBuffer buf;
rapidjson::Writer writer(buf);
json.Accept(writer);
return buf.GetString();
}
};
33. 算法模块设计
33.1 通用算法接口
迭代器模式实现:
cpp复制template <typename InputIt, typename OutputIt, typename Func>
OutputIt transform(InputIt first, InputIt last, OutputIt out, Func f) {
while (first != last) {
*out++ = f(*first++);
}
return out;
}
33.2 并行算法
使用execution策略:
cpp复制std::vector<int> data(1000000);
std::sort(std::execution::par, data.begin(), data.end());
34. 容器库扩展
34.1 安全容器
边界检查版本:
cpp复制template <typename T>
class SafeVector {
std::vector<T> data_;
public:
T& at(size_t i) {
if (i >= data_.size()) throw std::out_of_range("Index out of range");
return data_[i];
}
// 其他接口...
};
34.2 特殊容器
环形缓冲区实现:
cpp复制template <typename T, size_t Capacity>
class RingBuffer {
std::array<T, Capacity> buffer_;
size_t head_ = 0;
size_t tail_ = 0;
public:
bool push(T item) {
if (full()) return false;
buffer_[tail_] = std::move(item);
tail_ = (tail_ + 1) % Capacity;
return true;
}
bool pop(T& item) {
if (empty()) return false;
item = std::move(buffer_[head_]);
head_ = (head_ + 1) % Capacity;
return true;
}
};
35. 字符串处理
35.1 Unicode支持
UTF-8处理工具:
cpp复制size_t utf8Len(const std::string& str) {
size_t len = 0;
for (unsigned char c : str) {
if ((c & 0xC0) != 0x80) ++len;
}
return len;
}
35.2 字符串视图应用
避免不必要的拷贝:
cpp复制void processString(std::string_view sv) {
if (sv.starts_with("http://")) {
// 无需创建子字符串
}
}
36. 日期时间处理
36.1 高精度计时
跨平台实现:
cpp复制class Timer {
#ifdef _WIN32
LARGE_INTEGER freq_, start_;
#else
timespec start_;
#endif
public:
Timer() {
#ifdef _WIN32
QueryPerformanceFrequency(&freq_);
QueryPerformanceCounter(&start_);
#else
clock_gettime(CLOCK_MONOTONIC, &start_);
#endif
}
double elapsed() const {
#ifdef _WIN32
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return (now.QuadPart - start_.QuadPart) / double(freq_.QuadPart);
#else
timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return (now.tv_sec - start_.tv_sec) +
(now.tv_nsec - start_.tv_nsec) / 1e9;
#endif
}
};
36.2 时区转换
使用date.h库:
cpp复制#include <date/tz.h>
auto zt = date::make_zoned("Asia/Shanghai",
date::local_days{date::January/10/2023} + 9h);
std::cout << zt << "\n"; // 2023-01-10 09:00:00 CST
37. 文件系统操作
37.1 文件监控
使用inotify(Linux):
cpp复制class FileWatcher {
int inotifyFd_;
std::unordered_map<int, std::string> watchDescriptors_;
public:
void watch(const std::string& path) {
int wd = inotify_add_watch(inotifyFd_, path.c_str(),
IN_MODIFY | IN_CREATE | IN_DELETE);
watchDescriptors_[wd] = path;
}
std::vector<Event> pollEvents() {
char buf[4096];
auto len = read(inotifyFd_, buf, sizeof(buf));
// 解析事件...
}
};
37.2 内存映射文件
高效文件访问:
cpp复制class MappedFile {
void* data_ = nullptr;
size_t size_ = 0;
int fd_ = -1;
public:
explicit MappedFile(const std::string& path) {
fd_ = open(path.c_str(), O_RDONLY);
size_ = lseek(fd_, 0, SEEK_END);
data_ = mmap(nullptr, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
}
~MappedFile() {
if (data_) munmap(data_, size_);
if (fd_ != -1) close(fd_);
}
};
38. 密码学模块
38.1 哈希计算
使用OpenSSL:
cpp复制std::string sha256(const std::string& input) {
EVP_MD_CTX* ctx = EVP_MD_CTX_new();
EVP_DigestInit_ex(ctx, EVP_sha256(), nullptr);
EVP_DigestUpdate(ctx, input.data(), input.size());
unsigned char hash[EVP_MAX_MD_SIZE];
unsigned len;
EVP_DigestFinal_ex(ctx, hash, &len);
EVP_MD_CTX_free(ctx);
return std::string(reinterpret_cast<char*>(hash), len);
}
38.2 AES加密
安全实现示例:
cpp复制class AesEncryptor {
EVP_CIPHER_CTX* ctx_;
public:
AesEncryptor(const std::array<uint8_t, 32>& key,
const std::array<uint8_t, 16>& iv) {
ctx_ = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex
