现代 C++ 编程核心基础与高级特性指南
本文系统介绍了现代 C++ 编程的核心知识,涵盖语言基础、类型系统、面向对象设计、内存管理与智能指针、模板泛型、并发编程及性能优化等主题。通过代码示例展示了 C++11 至 C++20 的关键特性,包括 lambda 表达式、概念约束、协程及范围库,并结合设计模式与实战项目提供最佳实践建议,帮助开发者构建高效可靠的软件系统。

本文系统介绍了现代 C++ 编程的核心知识,涵盖语言基础、类型系统、面向对象设计、内存管理与智能指针、模板泛型、并发编程及性能优化等主题。通过代码示例展示了 C++11 至 C++20 的关键特性,包括 lambda 表达式、概念约束、协程及范围库,并结合设计模式与实战项目提供最佳实践建议,帮助开发者构建高效可靠的软件系统。

C++ 是由 Bjarne Stroustrup 于 1985 年在贝尔实验室开发的,最初称为"C with Classes"。它的设计哲学体现了几个核心原则:
// 不同 C++ 标准的特性示例
#include <iostream>
#include <vector>
#include <memory>
// C++98/03 - 传统 C++ 风格
class OldStyle {
public:
OldStyle() : data(new int[100]) {}
~OldStyle() { delete[] data; }
private:
int* data;
};
// C++11 - 现代 C++ 的起点
class ModernStyle {
public:
ModernStyle() : data(std::make_unique<int[]>(100)) {}
// 自动生成移动操作,禁止复制
ModernStyle(const ModernStyle&) = delete;
ModernStyle& operator=(const ModernStyle&) = delete;
ModernStyle(ModernStyle&&) = default;
ModernStyle& operator=(ModernStyle&&) = default;
private:
std::unique_ptr<int[]> data;
};
// C++17 - 更简洁的语法
auto calculate_stats(const std::vector<double>& values) {
if (values.empty()) {
return std::make_pair(0.0, 0.0);
}
double sum = 0;
for (auto v : values) sum += v;
double mean = sum / values.size();
double variance = 0;
for (auto v : values) variance += (v - mean) * (v - mean);
return std::pair{mean, variance / values.size()}; // CTAD: 类模板参数推导
}
// C++20 - 最新特性
#ifdef __cpp_concepts
template<typename T> concept Arithmetic = std::is_arithmetic_v<T>;
template<Arithmetic T> auto add(T a, T b) {
return a + b;
}
#endif
#include <iostream>
#include <type_traits>
#include <bit>
#include <limits>
void type_system_demo() {
// 整数类型 - 明确指定大小
int8_t small = 127; // 8 位有符号
uint8_t u_small = 255; // 8 位无符号
int16_t medium = 32767; // 16 位
int32_t large = 2147483647; // 32 位
int64_t huge = 9223372036854775807LL; // 64 位
// 浮点数类型
float f = 3.14159f; // 单精度,约 6-7 位有效数字
double d = 3.141592653589793; // 双精度,约 15 位有效数字
long double ld = 3.14159265358979323846L; // 扩展精度
// 字符类型
char ch = 'A'; // 通常 8 位
wchar_t wch = L'Ω'; // 宽字符
char16_t utf16 = u'字'; // UTF-16
char32_t utf32 = U'🐱'; // UTF-32
// 布尔类型
bool flag = true; // true 或 false
// 类型推断 - auto
auto x = 42; // int
auto y = 3.14; // double
auto z = std::string("Hello"); // std::string
// 编译时类型检查 - decltype
decltype(x) another_x = 100; // another_x 的类型与 x 相同
// 类型属性查询
std::cout << "int size: " << sizeof(int) << " bytes\n";
std::cout << "int max: " << std::numeric_limits<int>::max() << "\n";
std::cout << "float epsilon: " << std::numeric_limits<float>::epsilon() << "\n";
// C++20 位操作
uint32_t value = 0b10101010;
std::cout << "Popcount: " << std::popcount(value) << "\n";
std::cout << "Bit width: " << std::bit_width(value) << "\n";
}
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
// 现代 C++ 函数特性
class FunctionFeatures {
public:
// 1. 默认参数
int compute(int a, int b = 10, int c = 20) {
return a * b + c;
}
// 2. 内联函数
inline int square(int x) const {
return x * x;
}
// 3. constexpr 函数 - 编译时计算
constexpr int factorial(int n) {
return (n <= 1) ? 1 : n * factorial(n - 1);
}
// 4. consteval 函数 - C++20,必须编译时计算
consteval int compile_time_square(int n) {
return n * n;
}
// 5. noexcept 函数
void safe_operation() noexcept {
// 保证不抛出异常
}
// 6. 尾返回类型
auto get_data() -> std::vector<int> {
return {1, 2, 3, 4, 5};
}
// 7. 函数重载
void process(int value) {
std::cout << "Processing int: " << value << "\n";
}
void process(double value) {
std::cout << "Processing double: " << value << "\n";
}
void process(const std::string& value) {
std::cout << "Processing string: " << value << "\n";
}
};
// Lambda 表达式进阶
void lambda_demo() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 基本 lambda
auto is_even = [](int n) { return n % 2 == 0; };
// 带捕获的 lambda
int threshold = 5;
auto greater_than = [threshold](int n) { return n > threshold; };
// 通用 lambda - C++14
auto universal_add = [](auto a, auto b) { return a + b; };
// 初始化捕获 - C++14
auto unique_ptr = std::make_unique<int>(42);
auto accessor = [ptr = std::move(unique_ptr)]() { return *ptr; };
// 模板 lambda - C++20
auto templated_lambda = []<typename T>(const std::vector<T>& vec) { return vec.size(); };
// 使用标准算法与 lambda
int even_count = std::count_if(numbers.begin(), numbers.end(), is_even);
auto it = std::find_if(numbers.begin(), numbers.end(), greater_than);
// 生成新序列
std::vector<int> squares;
std::transform(numbers.begin(), numbers.end(), std::back_inserter(squares), [](int n) { return n * n; });
// 折叠表达式 - C++17
auto sum_all = [](auto... args) { return (args + ...); }; // 折叠表达式
std::cout << "Sum: " << sum_all(1, 2, 3, 4, 5) << "\n";
}
#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include <format> // C++20
// 现代 C++ 类设计示例
class Employee {
private:
std::string name;
int id;
double salary;
protected:
std::string department;
public:
// 构造函数
Employee(std::string name, int id, double salary, std::string dept)
: name(std::move(name)), id(id), salary(salary), department(std::move(dept)) {
std::cout << "Employee " << this->name << " created\n";
}
// 虚析构函数 - 多态基类必需
virtual ~Employee() {
std::cout << "Employee " << name << " destroyed\n";
}
// 拷贝构造函数
Employee(const Employee& other)
: name(other.name), id(other.id), salary(other.salary), department(other.department) {
std::cout << "Employee copied\n";
}
// 移动构造函数
Employee(Employee&& other) noexcept
: name(std::move(other.name)), id(other.id), salary(other.salary), department(std::move(other.department)) {
other.id = 0;
other.salary = 0.0;
std::cout << "Employee moved\n";
}
// 赋值运算符
Employee& operator=(const Employee& other) {
if (this != &other) {
name = other.name;
id = other.id;
salary = other.salary;
department = other.department;
}
return *this;
}
// 移动赋值运算符
Employee& operator=(Employee&& other) noexcept {
if (this != &other) {
name = std::move(other.name);
id = other.id;
salary = other.salary;
department = std::move(other.department);
other.id = 0;
other.salary = 0.0;
}
return *this;
}
// 纯虚函数 - 定义接口
virtual void work() const = 0;
// 虚函数 - 可被子类重写
virtual void display_info() const {
// C++20 格式化
std::cout << std::format("Name: {}, ID: {}, Salary: ${:.2f}, Dept: {}\n", name, id, salary, department);
}
// 常成员函数
std::string get_name() const { return name; }
int get_id() const { return id; }
// 静态成员
static int total_employees;
static void reset_count() { total_employees = 0; }
// 友元函数
friend void print_salary(const Employee& emp);
};
// 静态成员初始化
int Employee::total_employees = 0;
// 友元函数实现
void print_salary(const Employee& emp) {
std::cout << emp.name << "'s salary: " << emp.salary << "\n";
}
// 派生类
class Manager : public Employee {
private:
std::vector<std::shared_ptr<Employee>> team;
public:
Manager(std::string name, int id, double salary, std::string dept)
: Employee(std::move(name), id, salary, std::move(dept)) {}
void work() const override {
std::cout << "Manager " << get_name() << " is managing the team\n";
}
void display_info() const override {
Employee::display_info();
std::cout << "Team size: " << team.size() << "\n";
}
void add_employee(std::shared_ptr<Employee> emp) {
team.push_back(emp);
}
};
// 另一个派生类
class Developer : public Employee {
private:
std::string programming_language;
public:
Developer(std::string name, int id, double salary, std::string dept, std::string lang)
: Employee(std::move(name), id, salary, std::move(dept)), programming_language(std::move(lang)) {}
void work() const override {
std::cout << "Developer " << get_name() << " is coding in " << programming_language << "\n";
}
void display_info() const override {
Employee::display_info();
std::cout << "Language: " << programming_language << "\n";
}
};
#include <memory>
#include <vector>
#include <algorithm>
void polymorphism_demo() {
std::vector<std::unique_ptr<Employee>> employees;
// 创建不同类型的员工
employees.push_back(std::make_unique<Manager>("Alice", 1001, 80000.0, "Engineering"));
employees.push_back(std::make_unique<Developer>("Bob", 1002, 70000.0, "Engineering", "C++"));
employees.push_back(std::make_unique<Developer>("Charlie", 1003, 75000.0, "Engineering", "Python"));
// 多态调用
for (const auto& emp : employees) {
emp->work(); // 动态绑定
emp->display_info(); // 动态绑定
std::cout << "----------------\n";
}
// 类型识别与转换
for (const auto& emp : employees) {
// 动态类型检查
if (auto* manager = dynamic_cast<Manager*>(emp.get())) {
std::cout << emp->get_name() << " is a manager\n";
} else if (auto* developer = dynamic_cast<Developer*>(emp.get())) {
std::cout << emp->get_name() << " is a developer\n";
}
}
// 使用 typeid 获取类型信息
for (const auto& emp : employees) {
std::cout << "Type: " << typeid(*emp).name() << "\n";
}
}
#include <iostream>
#include <memory>
#include <vector>
class Resource {
private:
int id;
std::string name;
public:
Resource(int id, std::string name) : id(id), name(std::move(name)) {
std::cout << "Resource " << id << " created\n";
}
~Resource() {
std::cout << "Resource " << id << " destroyed\n";
}
void use() const {
std::cout << "Using resource " << id << ": " << name << "\n";
}
};
// RAII 资源管理类
class ResourceManager {
private:
std::unique_ptr<Resource> resource;
public:
explicit ResourceManager(int id, std::string name)
: resource(std::make_unique<Resource>(id, std::move(name))) {}
Resource* get() const { return resource.get(); }
// 释放所有权
std::unique_ptr<Resource> release() {
return std::move(resource);
}
};
void smart_pointers_demo() {
std::cout << "=== Unique_ptr Demo ===\n";
{
// 独占所有权
std::unique_ptr<Resource> res1 = std::make_unique<Resource>(1, "Database");
std::unique_ptr<Resource> res2 = std::make_unique<Resource>(2, "Network");
// 转移所有权
std::unique_ptr<Resource> res3 = std::move(res1);
if (!res1) {
std::cout << "res1 is now empty\n";
}
// 自定义删除器
auto custom_deleter = [](Resource* r) {
std::cout << "Custom delete for resource\n";
delete r;
};
std::unique_ptr<Resource, decltype(custom_deleter)> res4(new Resource(3, "File"), custom_deleter);
}
std::cout << "\n=== Shared_ptr Demo ===\n";
{
// 共享所有权
std::shared_ptr<Resource> shared1 = std::make_shared<Resource>(4, "Shared Resource");
{
std::shared_ptr<Resource> shared2 = shared1; // 引用计数 +1
std::shared_ptr<Resource> shared3 = shared1; // 引用计数 +1
std::cout << "Use count: " << shared1.use_count() << "\n";
// 创建弱引用
std::weak_ptr<Resource> weak_ref = shared1;
if (auto shared4 = weak_ref.lock()) {
std::cout << "Successfully locked weak_ptr\n";
std::cout << "Use count after lock: " << shared1.use_count() << "\n";
}
}
// shared2, shared3 销毁,引用计数 -2
std::cout << "Use count: " << shared1.use_count() << "\n";
}
std::cout << "\n=== Weak_ptr Demo ===\n";
{
// 循环引用问题解决
struct Node {
std::shared_ptr<Node> next;
std::weak_ptr<Node> prev; // 使用 weak_ptr 打破循环引用
~Node() { std::cout << "Node destroyed\n"; }
};
auto node1 = std::make_shared<Node>();
auto node2 = std::make_shared<Node>();
node1->next = node2;
node2->prev = node1;
// 使用 weak_ptr,不会增加引用计数
std::cout << "Node1 use count: " << node1.use_count() << "\n";
std::cout << "Node2 use count: " << node2.use_count() << "\n";
}
std::cout << "\n=== RAII Demo ===\n";
{
ResourceManager manager(5, "Managed Resource");
manager.get()->use(); // 自动释放资源
}
}
#include <iostream>
#include <memory>
#include <cstdlib>
// 自定义分配器
template<typename T>
class CustomAllocator {
public:
using value_type = T;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
template<typename U> struct rebind {
using other = CustomAllocator<U>;
};
CustomAllocator() noexcept = default;
template<typename U>
CustomAllocator(const CustomAllocator<U>&) noexcept {}
pointer allocate(size_type n) {
std::cout << "Allocating " << n << " objects of size " << sizeof(T) << "\n";
if (n > max_size()) {
throw std::bad_alloc();
}
pointer p = static_cast<pointer>(std::malloc(n * sizeof(T)));
if (!p) {
throw std::bad_alloc();
}
return p;
}
void deallocate(pointer p, size_type n) noexcept {
std::cout << "Deallocating " << n << " objects\n";
std::free(p);
}
size_type max_size() const noexcept {
return std::size_t(-1) / sizeof(T);
}
template<typename U, typename... Args>
void construct(U* p, Args&&... args) {
new(p) U(std::forward<Args>(args)...);
}
template<typename U>
void destroy(U* p) {
p->~U();
}
};
// 内存池实现
template<typename T, std::size_t BlockSize = 1024>
class MemoryPool {
private:
union Slot {
T element;
Slot* next;
};
struct Block {
Slot slots[BlockSize];
Block* next;
};
Slot* free_list;
Block* blocks;
public:
MemoryPool() : free_list(nullptr), blocks(nullptr) {
allocate_block();
}
~MemoryPool() {
while (blocks) {
Block* next = blocks->next;
delete blocks;
blocks = next;
}
}
T* allocate() {
if (!free_list) {
allocate_block();
}
Slot* slot = free_list;
free_list = free_list->next;
return &slot->element;
}
void deallocate(T* p) {
Slot* slot = reinterpret_cast<Slot*>(p);
slot->next = free_list;
free_list = slot;
}
private:
void allocate_block() {
Block* block = new Block;
block->next = blocks;
blocks = block;
// 初始化空闲列表
for (std::size_t i = 0; i < BlockSize - 1; ++i) {
block->slots[i].next = &block->slots[i + 1];
}
block->slots[BlockSize - 1].next = free_list;
free_list = &block->slots[0];
}
};
#include <iostream>
#include <vector>
#include <type_traits>
// 函数模板
template<typename T>
T max_value(T a, T b) {
return (a > b) ? a : b;
}
// 类模板
template<typename T, std::size_t N>
class FixedArray {
private:
T data[N];
public:
constexpr std::size_t size() const { return N; }
T& operator[](std::size_t index) {
if (index >= N) {
throw std::out_of_range("Index out of range");
}
return data[index];
}
const T& operator[](std::size_t index) const {
if (index >= N) {
throw std::out_of_range("Index out of range");
}
return data[index];
}
// 范围 for 支持
T* begin() { return data; }
T* end() { return data + N; }
const T* begin() const { return data; }
const T* end() const { return data + N; }
};
// 模板特化
template<typename T>
class TypeInfo {
public:
static std::string name() { return "unknown"; }
};
template<>
class TypeInfo<int> {
public:
static std::string name() { return "int"; }
};
template<>
class TypeInfo<double> {
public:
static std::string name() { return "double"; }
};
// 可变参数模板
template<typename... Args>
void print_all(Args... args) {
(std::cout << ... << args) << '\n'; // C++17 折叠表达式
}
template<typename T, typename... Rest>
void print_with_separator(T first, Rest... rest) {
std::cout << first;
((std::cout << ", " << rest), ...) << '\n';
}
#include <concepts> // C++20
#include <ranges> // C++20
// 概念约束 - C++20
template<typename T>
concept Arithmetic = requires(T a, T b) {
{ a + b } -> std::same_as<T>;
{ a - b } -> std::same_as<T>;
{ a * b } -> std::same_as<T>;
{ a / b } -> std::same_as<T>;
requires std::is_arithmetic_v<T>;
};
template<Arithmetic T>
T power(T base, int exponent) {
T result = 1;
for (int i = 0; i < exponent; ++i) {
result *= base;
}
return result;
}
// 要求子句
template<typename Container>
requires requires(Container c) {
{ c.begin() } -> std::forward_iterator;
{ c.end() } -> std::forward_iterator;
typename Container::value_type;
}
void print_container(const Container& container) {
for (const auto& item : container) {
std::cout << item << " ";
}
std::cout << "\n";
}
// SFINAE 传统方式
template<typename T>
typename std::enable_if<std::is_integral<T>::value, T>::type increment(T value) {
return value + 1;
}
template<typename T>
typename std::enable_if<std::is_floating_point<T>::value, T>::type increment(T value) {
return value + 0.1;
}
// 类型特性使用
template<typename T>
void process_value(T value) {
if constexpr (std::is_pointer_v<T>) {
std::cout << "Processing pointer: " << *value << "\n";
} else if constexpr (std::is_integral_v<T>) {
std::cout << "Processing integer: " << value << "\n";
} else if constexpr (std::is_floating_point_v<T>) {
std::cout << "Processing float: " << value << "\n";
} else {
std::cout << "Processing unknown type\n";
}
}
// 完美转发
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
// C++20 范围库
void ranges_demo() {
namespace rv = std::views;
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 管道操作
auto result = numbers | rv::filter([](int n) { return n % 2 == 0; })
| rv::transform([](int n) { return n * n; })
| rv::take(3);
std::cout << "Filtered and transformed: ";
for (int n : result) {
std::cout << n << " ";
}
std::cout << "\n";
// 生成无限序列
auto infinite = rv::iota(1) | rv::transform([](int n) { return n * 2; }) | rv::take(10);
std::cout << "First 10 even numbers: ";
for (int n : infinite) {
std::cout << n << " ";
}
std::cout << "\n";
}
#include <iostream>
#include <thread>
#include <mutex>
#include <atomic>
#include <future>
#include <vector>
#include <chrono>
#include <condition_variable>
#include <queue>
class ThreadSafeQueue {
private:
std::queue<int> data;
mutable std::mutex mutex;
std::condition_variable cond;
public:
void push(int value) {
std::lock_guard lock(mutex);
data.push(value);
cond.notify_one();
}
bool try_pop(int& value) {
std::lock_guard lock(mutex);
if (data.empty()) {
return false;
}
value = data.front();
data.pop();
return true;
}
void wait_and_pop(int& value) {
std::unique_lock lock(mutex);
cond.wait(lock, [this] { return !data.empty(); });
value = data.front();
data.pop();
}
};
// 原子操作
class Counter {
private:
std::atomic<int> count{0};
public:
void increment() { ++count; }
void decrement() { --count; }
int get() const { return count.load(std::memory_order_acquire); }
void reset() { count.store(0, std::memory_order_release); }
};
// 并行算法
void parallel_processing() {
std::vector<int> numbers(1000000);
std::iota(numbers.begin(), numbers.end(), 0);
// 并行 transform
std::vector<int> results(numbers.size());
auto start = std::chrono::high_resolution_clock::now();
std::transform(
std::execution::par, // 并行执行策略
numbers.begin(), numbers.end(), results.begin(),
[](int n) {
// 模拟耗时计算
return n * n + std::sqrt(n) + std::log(n + 1);
}
);
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "Parallel transform took " << duration.count() << "ms\n";
}
#include <future>
#include <async>
class AsyncProcessor {
public:
// 异步任务
std::future<int> process_async(int input) {
return std::async(std::launch::async, [input]() {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
return input * input;
});
}
// 多个异步任务
std::future<std::vector<int>> process_batch(const std::vector<int>& inputs) {
return std::async(std::launch::async, [inputs]() {
std::vector<std::future<int>> futures;
for (int input : inputs) {
futures.push_back(std::async(std::launch::async, [input]() {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
return input * 2;
}));
}
std::vector<int> results;
for (auto& fut : futures) {
results.push_back(fut.get());
}
return results;
});
}
// 使用 packaged_task
std::future<double> create_task() {
std::packaged_task<double()> task([]() {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
return 3.1415926535;
});
std::future<double> result = task.get_future();
std::thread task_thread(std::move(task));
task_thread.detach();
return result;
}
};
// 协程 - C++20
#ifdef __cpp_coroutines
#include <coroutine>
template<typename T>
struct Generator {
struct promise_type {
T current_value;
Generator get_return_object() {
return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void unhandled_exception() { std::terminate(); }
void return_void() {}
std::suspend_always yield_value(T value) {
current_value = value;
return {};
}
};
std::coroutine_handle<promise_type> coro;
explicit Generator(std::coroutine_handle<promise_type> h) : coro(h) {}
~Generator() { if (coro) coro.destroy(); }
bool next() {
if (!coro.done()) {
coro.resume();
return !coro.done();
}
return false;
}
T value() const { return coro.promise().current_value; }
// 迭代器支持
struct iterator {
Generator* gen;
iterator& operator++() { gen->next(); return *this; }
T operator*() const { return gen->value(); }
bool operator!=(const iterator& other) const { return gen != other.gen; }
};
iterator begin() { next(); return iterator{this}; }
iterator end() { return iterator{nullptr}; }
};
Generator<int> fibonacci(int n) {
int a = 0, b = 1;
for (int i = 0; i < n; ++i) {
co_yield a;
int next = a + b;
a = b;
b = next;
}
}
#endif
// 工厂模式
class Shape {
public:
virtual ~Shape() = default;
virtual void draw() const = 0;
virtual std::unique_ptr<Shape> clone() const = 0;
};
class ShapeFactory {
public:
static std::unique_ptr<Shape> create(const std::string& type) {
static std::unordered_map<std::string, std::function<std::unique_ptr<Shape>()>> creators = {
{"circle", []() { return std::make_unique<Circle>(); }},
{"rectangle", []() { return std::make_unique<Rectangle>(); }},
{"triangle", []() { return std::make_unique<Triangle>(); }}
};
auto it = creators.find(type);
if (it != creators.end()) {
return it->second();
}
return nullptr;
}
};
// 观察者模式
template<typename T>
class Observable {
std::vector<std::function<void(const T&)>> observers;
public:
void subscribe(std::function<void(const T&)> observer) {
observers.push_back(std::move(observer));
}
void notify(const T& data) {
for (const auto& observer : observers) {
observer(data);
}
}
};
// 策略模式
template<typename T>
class SortStrategy {
public:
virtual ~SortStrategy() = default;
virtual void sort(std::vector<T>& data) = 0;
};
// 单例模式 - 现代线程安全实现
class DatabaseConnection {
private:
DatabaseConnection() = default;
public:
static DatabaseConnection& instance() {
static DatabaseConnection instance;
return instance;
}
DatabaseConnection(const DatabaseConnection&) = delete;
DatabaseConnection& operator=(const DatabaseConnection&) = delete;
void connect() { /* ... */ }
void disconnect() { /* ... */ }
};
// 1. 内存局部性优化
class OptimizedMatrix {
private:
std::vector<double> data;
size_t rows, cols;
public:
OptimizedMatrix(size_t r, size_t c) : data(r * c), rows(r), cols(c) {}
// 行主序访问
double& operator()(size_t i, size_t j) {
return data[i * cols + j];
}
// 矩阵乘法优化
OptimizedMatrix multiply(const OptimizedMatrix& other) const {
OptimizedMatrix result(rows, other.cols);
// 缓存友好的三重循环
const size_t block_size = 32;
for (size_t i = 0; i < rows; i += block_size) {
for (size_t j = 0; j < other.cols; j += block_size) {
for (size_t k = 0; k < cols; k += block_size) {
size_t i_end = std::min(i + block_size, rows);
size_t j_end = std::min(j + block_size, other.cols);
size_t k_end = std::min(k + block_size, cols);
for (size_t ii = i; ii < i_end; ++ii) {
for (size_t kk = k; kk < k_end; ++kk) {
double a = (*this)(ii, kk);
for (size_t jj = j; jj < j_end; ++jj) {
result(ii, jj) += a * other(kk, jj);
}
}
}
}
}
}
return result;
}
};
// 2. 编译器优化提示
void optimization_hints() {
std::vector<int> data(1000);
// 预分配内存
data.reserve(10000);
// 使用移动语义
std::vector<int> large_data(1000000);
std::vector<int> moved_data = std::move(large_data);
// 小对象优化
std::string small = "short"; // 可能存储在栈上
std::string large = "a very long string that will be heap allocated";
// 编译器屏障
std::atomic_signal_fence(std::memory_order_seq_cst);
}
// 3. 内联汇编示例
void inline_assembly_example() {
int a = 10, b = 20, result;
__asm__ volatile (
"add %[input1], %[input2]\n\t"
"mov %[input2], %[output]"
: [output] "=r" (result)
: [input1] "r" (a), [input2] "r" (b)
);
std::cout << "Assembly result: " << result << "\n";
}
// 高性能 HTTP 服务器框架
class HttpServer {
private:
boost::asio::io_context io_context;
tcp::acceptor acceptor;
std::unordered_map<std::string, std::function<HttpResponse(const HttpRequest&)>> routes;
ThreadPool thread_pool;
public:
HttpServer(unsigned short port, size_t thread_count = 4)
: acceptor(io_context, tcp::endpoint(tcp::v4(), port))
, thread_pool(thread_count) {
start_accept();
}
void run() {
io_context.run();
}
void get(const std::string& path, std::function<HttpResponse(const HttpRequest&)> handler) {
routes["GET:" + path] = std::move(handler);
}
void post(const std::string& path, std::function<HttpResponse(const HttpRequest&)> handler) {
routes["POST:" + path] = std::move(handler);
}
private:
void start_accept() {
auto socket = std::make_shared<tcp::socket>(io_context);
acceptor.async_accept(*socket, [this, socket](const boost::system::error_code& error) {
if (!error) {
thread_pool.enqueue([this, socket]() {
handle_connection(socket);
});
}
start_accept();
});
}
void handle_connection(std::shared_ptr<tcp::socket> socket) {
try {
HttpRequest request = parse_request(socket);
std::string key = request.method + ":" + request.path;
if (auto it = routes.find(key); it != routes.end()) {
HttpResponse response = it->second(request);
send_response(socket, response);
} else {
send_response(socket, HttpResponse(404, "Not Found"));
}
} catch (const std::exception& e) {
send_response(socket, HttpResponse(500, "Internal Server Error"));
}
}
};
// 编译期字符串处理
template<size_t N>
struct FixedString {
char data[N];
constexpr FixedString(const char (&str)[N]) {
std::copy_n(str, N, data);
}
constexpr size_t size() const { return N - 1; }
constexpr char operator[](size_t i) const {
return i < N ? data[i] : throw std::out_of_range("");
}
template<size_t M>
constexpr auto operator+(const FixedString<M>& other) const {
FixedString<N + M - 1> result{};
std::copy_n(data, N - 1, result.data);
std::copy_n(other.data, M, result.data + N - 1);
return result;
}
};
// 编译期哈希
template<FixedString Str>
consteval size_t hash() {
size_t hash = 5381;
for (size_t i = 0; i < Str.size(); ++i) {
hash = ((hash << 5) + hash) + Str[i];
}
return hash;
}
// 编译期 JSON 解析(简化版)
template<FixedString Json>
constexpr auto parse_json() {
// 编译期 JSON 解析逻辑
// 返回类型安全的 JSON 对象
return JsonObject<Json>{};
}
#ifdef _WIN32
#define PLATFORM_WINDOWS
#include <windows.h>
#elif defined(__linux__)
#define PLATFORM_LINUX
#include <unistd.h>
#include <sys/mman.h>
#elif defined(__APPLE__)
#define PLATFORM_MACOS
#include <mach/mach.h>
#endif
class PlatformFile {
private:
#ifdef PLATFORM_WINDOWS
HANDLE file_handle;
#else
int file_descriptor;
#endif
public:
PlatformFile(const std::string& filename) {
#ifdef PLATFORM_WINDOWS
file_handle = CreateFileA(
filename.c_str(), GENERIC_READ | GENERIC_WRITE,
0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr
);
#else
file_descriptor = open(filename.c_str(), O_RDWR);
#endif
}
~PlatformFile() {
#ifdef PLATFORM_WINDOWS
if (file_handle != INVALID_HANDLE_VALUE) {
CloseHandle(file_handle);
}
#else
if (file_descriptor != -1) {
close(file_descriptor);
}
#endif
}
void* map(size_t size) {
#ifdef PLATFORM_WINDOWS
HANDLE mapping = CreateFileMapping(
file_handle, nullptr, PAGE_READWRITE, 0, size, nullptr
);
return MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
#else
return mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, file_descriptor, 0);
#endif
}
};
C++ 作为一门复杂而强大的语言,其学习曲线陡峭但回报丰厚。现代 C++(C++11/14/17/20)已经大大简化了开发流程,提供了更安全、更高效的工具。掌握 C++ 需要:
通过不断实践和深入学习,你不仅能成为 C++ 专家,还能培养出解决复杂问题的系统思维能力。C++ 的未来依然光明,随着 C++23、C++26 等新标准的推出,这门语言将继续演进,保持其在系统编程、高性能计算、游戏开发等领域的领导地位。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
暂无推荐文章,稍后可再来查看。
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML 转 Markdown 互为补充。 在线工具,Markdown 转 HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML 转 Markdown在线工具,online
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online