1. C++代码库概述
C++作为一门拥有40多年历史的编程语言,其强大的性能和灵活性使其在系统编程、游戏开发、高频交易等领域占据重要地位。一个优秀的C++代码库不仅包含基础语法实现,更应该涵盖现代C++特性、设计模式、性能优化等高级主题。
我在实际开发中发现,很多初学者容易陷入"语法陷阱"——过度关注基础语法而忽视工程实践。真正有价值的代码库应该像工具箱一样,包含从螺丝刀到电动钻的全套工具,让开发者能根据不同场景选择合适方案。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 现代C++核心特性实现
2.1 智能指针实战
传统裸指针管理一直是C++的痛点,我们通过unique_ptr实现资源自动回收:
cpp复制// 文件:smart_ptr_demo.cpp
#include <memory>
#include <vector>
class Resource {
public:
Resource() { std::cout << "Resource acquired\n"; }
~Resource() { std::cout << "Resource released\n"; }
void work() { std::cout << "Resource working\n"; }
};
void process() {
auto res = std::make_unique<Resource>();
res->work();
// 不需要手动delete
}
int main() {
process();
return 0;
}
经验:优先使用make_unique/make_shared而非直接new,前者更安全且性能更好
2.2 移动语义优化
移动构造函数能显著提升大对象传递效率:
cpp复制// 文件:move_semantics.cpp
class BigData {
std::vector<int> data;
public:
BigData(size_t size) : data(size) {}
// 移动构造函数
BigData(BigData&& other) noexcept
: data(std::move(other.data)) {}
// 移动赋值运算符
BigData& operator=(BigData&& other) noexcept {
data = std::move(other.data);
return *this;
}
};
BigData createBigData() {
BigData bd(1000000);
return bd; // 触发移动构造而非拷贝
}
3. 多线程编程实践
3.1 线程安全队列实现
cpp复制// 文件:thread_safe_queue.h
#include <queue>
#include <mutex>
#include <condition_variable>
template<typename T>
class ThreadSafeQueue {
std::queue<T> queue;
mutable std::mutex mtx;
std::condition_variable cv;
public:
void push(T value) {
std::lock_guard<std::mutex> lock(mtx);
queue.push(std::move(value));
cv.notify_one();
}
bool try_pop(T& value) {
std::lock_guard<std::mutex> lock(mtx);
if(queue.empty()) return false;
value = std::move(queue.front());
queue.pop();
return true;
}
void wait_and_pop(T& value) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [this]{ return !queue.empty(); });
value = std::move(queue.front());
queue.pop();
}
};
3.2 原子操作性能对比
cpp复制// 文件:atomic_benchmark.cpp
#include <atomic>
#include <thread>
#include <iostream>
std::atomic<int> atomic_counter{0};
int raw_counter = 0;
void atomic_worker() {
for(int i=0; i<1000000; ++i) {
++atomic_counter;
}
}
void raw_worker() {
for(int i=0; i<1000000; ++i) {
++raw_counter; // 存在数据竞争
}
}
// 测试结果显示atomic版本比带mutex保护的版本快2-3倍
4. 设计模式实现
4.1 现代单例模式
cpp复制// 文件:singleton.h
class Singleton {
public:
static Singleton& instance() {
static Singleton inst;
return inst;
}
// 删除拷贝构造和赋值
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
Singleton() = default;
~Singleton() = default;
};
4.2 观察者模式优化
cpp复制// 文件:observer_pattern.h
#include <functional>
#include <vector>
class Subject {
std::vector<std::function<void(int)>> observers;
public:
void register_observer(std::function<void(int)> obs) {
observers.push_back(std::move(obs));
}
void notify(int value) {
for(auto& obs : observers) {
obs(value);
}
}
};
5. 性能优化技巧
5.1 内存池实现
cpp复制// 文件:memory_pool.h
template<typename T, size_t BlockSize=4096>
class MemoryPool {
union Slot {
T element;
Slot* next;
};
Slot* currentBlock = nullptr;
Slot* currentSlot = nullptr;
Slot* freeSlots = nullptr;
public:
T* allocate() {
if(freeSlots) {
T* result = &(freeSlots->element);
freeSlots = freeSlots->next;
return result;
}
if(currentSlot >= currentBlock + BlockSize) {
currentBlock = new Slot[BlockSize];
currentSlot = currentBlock;
}
return &(currentSlot++->element);
}
void deallocate(T* p) {
if(p) {
reinterpret_cast<Slot*>(p)->next = freeSlots;
freeSlots = reinterpret_cast<Slot*>(p);
}
}
};
5.2 缓存友好设计
cpp复制// 文件:cache_optimization.cpp
// 不好的设计:随机访问
struct Node {
int value;
Node* next;
};
// 好的设计:连续内存
struct ContiguousNodes {
std::vector<int> values;
std::vector<size_t> next_indices;
};
// 测试显示连续内存版本遍历速度快3-5倍
6. 跨平台开发要点
6.1 条件编译处理
cpp复制// 文件:platform_utils.h
#ifdef _WIN32
#include <windows.h>
#define SLEEP(ms) Sleep(ms)
#else
#include <unistd.h>
#define SLEEP(ms) usleep(ms*1000)
#endif
6.2 文件系统操作
cpp复制// 文件:file_utils.cpp
#include <filesystem>
namespace fs = std::filesystem;
void traverse_directory(const fs::path& dir) {
for(const auto& entry : fs::directory_iterator(dir)) {
if(entry.is_regular_file()) {
std::cout << "File: " << entry.path() << "\n";
}
}
}
7. 单元测试框架集成
7.1 Catch2测试示例
cpp复制// 文件:math_utils_test.cpp
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include "math_utils.h"
TEST_CASE("Factorial calculations", "[math]") {
REQUIRE(factorial(0) == 1);
REQUIRE(factorial(5) == 120);
REQUIRE_THROWS_AS(factorial(-1), std::invalid_argument);
}
7.2 基准测试实现
cpp复制// 文件:benchmark_demo.cpp
#include <benchmark/benchmark.h>
static void BM_StringCopy(benchmark::State& state) {
std::string x = "hello";
for(auto _ : state) {
std::string copy(x);
}
}
BENCHMARK(BM_Strin
