C++ 是一门具有悠久历史的编程语言,自 1983 年由 Bjarne Stroustrup 开发以来,便以其高性能、面向对象与底层操作能力在系统开发、图形引擎、金融高频交易、嵌入式系统等领域广泛应用。特别是在 C++11、C++14、C++17、C++20 乃至 C++23 之后,现代 C++ 逐步引入了智能指针、Lambda 表达式、并发编程、模块化等大量提升生产力的新特性,使其兼具效率与现代化。
本文将从以下几个角度全面剖析现代 C++:
-
C++ 的核心语言特性解析
-
C++11/14/17/20 新特性精要
-
面向对象设计模式实战
-
C++ 中的内存管理机制与优化
-
CMake 与工程构建
-
多线程与并发模型
-
C++ 性能优化技巧
一、C++ 核心语言特性简析
1.1 值与引用语义
C++ 拥有值语义和引用语义两种方式,赋予程序员极高的控制能力。
cpp复制编辑void foo(int a) { a += 1; }void bar(int& b) { b += 1; }int main() { int x = 10; foo(x); // 值传递,不影响 x
bar(x); // 引用传递,修改 x}
1.2 函数重载与默认参数
C++ 支持函数重载与默认参数,在接口设计中具有强大灵活性。
cpp复制编辑void log(const std::string& msg, int level = 1) {
std::cout << "[L" << level << "] " << msg << std::endl;
}
1.3 模板编程
模板是 C++ 泛型编程的基石。
cpp复制编辑template<typename T>
T add(T a, T b) { return a + b;
}
1.4 RAII 与资源管理
RAII(Resource Acquisition Is Initialization)是 C++ 管理资源的核心思想。典型例子如 std::lock_guard:
cpp复制编辑std::mutex mtx;void thread_safe() { std::lock_guard<std::mutex> lock(mtx); // 自动加锁与解锁
// 临界区操作}
二、现代 C++ 新特性精要(C++11 起)
2.1 智能指针
C++11 引入了 std::shared_ptr, std::unique_ptr, std::weak_ptr 来管理动态资源。
cpp复制编辑std::unique_ptr<int> p1(new int(10));auto p2 = std::make_shared<std::vector<int>>(100);
2.2 Lambda 表达式
Lambda 提供了一种内联定义匿名函数的方式:
cpp复制编辑auto square = [](int x) { return x * x; };
std::cout << square(5); // 输出 25
2.3 auto 类型推导
极大减少模板代码的繁杂:
cpp复制编辑std::map<int, std::string> dict;for (auto& [key, value] : dict) {
std::cout << key << ": " << value;
}
2.4 constexpr 与编译期计算
提高效率的关键:
cpp复制编辑constexpr int factorial(int n) { return n <= 1 ? 1 : (n * factorial(n - 1));
}
三、面向对象设计模式实践
3.1 单例模式
cpp复制编辑class Singleton {public: static Singleton& instance() { static Singleton s; return s;
}private: Singleton() {} Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
3.2 工厂模式
cpp复制编辑class Shape {public: virtual void draw() = 0;
};class Circle : public Shape { void draw() override { std::cout << "Draw Circle\n"; }
};class ShapeFactory {public: static std::unique_ptr<Shape> create(const std::string& type) { if (type == "circle") return std::make_unique<Circle>(); return nullptr;
}
};
四、内存管理与优化
4.1 堆栈区别
-
栈上对象生命周期自动管理,速度快
-
堆上对象需要手动释放或用智能指针托管
4.2 内存泄漏排查
使用 Valgrind、ASan 工具,或封装监控:
cpp复制编辑class LeakChecker { size_t alloc_count = 0;public: void* operator new(size_t size) {
++alloc_count; return malloc(size);
}
};
4.3 避免拷贝与移动语义
cpp复制编辑class Buffer {
std::vector<int> data;public: Buffer() = default; Buffer(const Buffer&) = delete; Buffer(Buffer&&) noexcept = default;
};
五、C++ 项目工程化构建(CMake)
5.1 基本构建
cmake复制编辑cmake_minimum_required(VERSION 3.10)
project(MyApp)
set(CMAKE_CXX_STANDARD 17)
add_executable(MyApp main.cpp)
5.2 模块化构建与库链接
cmake复制编辑add_library(utils STATIC utils.cpp)
target_include_directories(utils PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(MyApp utils)
六、多线程与并发模型
6.1 std::thread 使用
cpp复制编辑void task() { std::cout << "Running\n"; }std::thread t(task);
t.join();
6.2 线程安全数据结构
使用 std::mutex, std::lock_guard, std::atomic 实现线程安全:
cpp复制编辑std::atomic<int> counter(0);void increment() { for (int i = 0; i < 1000; ++i) {
counter.fetch_add(1);
}
}
6.3 线程池模型简述
线程池将任务分发至固定数量线程,提升并发效率,可自定义实现如下:
cpp复制编辑class ThreadPool {
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition; bool stop = false;public: ThreadPool(size_t n) { for (size_t i = 0; i < n; ++i)
workers.emplace_back([this] { for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queue_mutex);
condition.wait(lock, [this] { return stop || !tasks.empty(); }); if (stop && tasks.empty()) return;
task = std::move(tasks.front());
tasks.pop();
} task();
}
});
} template<class F> void enqueue(F f) {
{ std::unique_lock<std::mutex> lock(queue_mutex);
tasks.emplace(f);
}
condition.notify_one();
}
~ThreadPool() {
stop = true;
condition.notify_all(); for (auto& t : workers) t.join();
}
};
七、C++ 性能优化技巧
7.1 使用 reserve() 避免频繁 realloc
cpp复制编辑std::vector<int> vec;
vec.reserve(10000); // 避免频繁扩容
7.2 避免不必要的拷贝
使用引用传参或移动语义。
cpp复制编辑void process(std::string&& s) {
std::string local = std::move(s);
}
7.3 使用 emplace_back() 替代 push_back()
可减少构造与拷贝步骤。