四、ABI与链接
4.1 C++ ABI深入
#include <iostream>
// ========== 名字修饰(Name Mangling) ==========
// 不同编译器的名字修饰规则不同
// 使用extern "C"禁用名字修饰
extern "C" {
void c_function() {
std::cout << "C function" << std::endl;
}
}
// 函数重载的名字修饰
void func(int) {}
void func(double) {}
void func(int, int) {}
// ========== 符号可见性 ==========
// 默认可见(全局符号)
__attribute__((visibility("default"))) void public_func() {}
// 隐藏符号(不导出)
__attribute__((visibility("hidden"))) void private_func() {}
// 内联函数(默认隐藏)
inline void inline_func() {}
// ========== 二进制兼容性 ==========
// 破坏ABI兼容性的操作:
// 1. 添加虚函数
// 2. 改变类成员顺序
// 3. 添加非静态成员
// 4. 改变基类
// ABI兼容的类设计
class StableAPI {
private:
// 使用Pimpl模式隐藏实现
struct Impl;
std::unique_ptr<Impl> pImpl;
public:
StableAPI();
~StableAPI();
void publicMethod();
};
// ========== 动态库加载 ==========
#ifdef _WIN32
#include <windows.h>
#define DLL_EXPORT __declspec(dllexport)
#define DLL_IMPORT __declspec(dllimport)
#else
#define DLL_EXPORT __attribute__((visibility("default")))
#define DLL_IMPORT
#endif
class DLL_EXPORT ExportClass {
public:
void exportMethod();
};
五、性能极致优化
5.1 编译期优化技术
#include <iostream>
#include <array>
#include <algorithm>
// ========== constexpr函数优化 ==========
constexpr int fibonacci(int n) {
return (n <= 1) ? n : fibonacci(n - 1) + fibonacci(n - 2);
}
// 编译期数组生成
template<size_t N>
struct FibonacciArray {
std::array<int, N> data;
constexpr FibonacciArray() : data() {
for (size_t i = 0; i < N; i++) {
data[i] = fibonacci(i);
}
}
};
constexpr auto fib_array = FibonacciArray<20>();
// ========== 元函数优化 ==========
template<int N>
struct Sqrt {
static constexpr int value = Sqrt<N / 2>::value;
};
template<>
struct Sqrt<0> {
static constexpr int value = 0;
};
template<>
struct Sqrt<1> {
static constexpr int value = 1;
};
// ========== 分支预测优化 ==========
// 使用__builtin_expect提示编译器
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
void branch_prediction(int x) {
if (likely(x > 0)) {
// 热路径
for (int i = 0; i < 1000; i++) {
// ...
}
} else if (unlikely(x < 0)) {
// 冷路径
// ...
}
}
// ========== 对齐优化 ==========
struct alignas(64) CacheAligned {
int data[16];
char padding[64 - sizeof(int[16]) % 64];
};
// ========== 内联优化 ==========
// 强制内联
__attribute__((always_inline)) inline int force_inline(int x) {
return x * x;
}
// 不内联
__attribute__((noinline)) int no_inline(int x) {
return x * x;
}
// ========== 纯函数优化 ==========
// 结果只依赖参数,无副作用
__attribute__((pure)) int square(int x) {
return x * x;
}
// 常量函数
__attribute__((const)) int cube(int x) {
return x * x * x;
}
5.2 SIMD与向量化
#include <immintrin.h>
#include <vector>
#include <iostream>
// ========== SSE指令 ==========
void sse_add(float* a, float* b, float* c, int n) {
for (int i = 0; i < n; i += 4) {
__m128 va = _mm_loadu_ps(a + i);
__m128 vb = _mm_loadu_ps(b + i);
__m128 vc = _mm_add_ps(va, vb);
_mm_storeu_ps(c + i, vc);
}
}
// ========== AVX指令 ==========
void avx_add(double* a, double* b, double* c, int n) {
for (int i = 0; i < n; i += 4) {
__m256d va = _mm256_loadu_pd(a + i);
__m256d vb = _mm256_loadu_pd(b + i);
__m256d vc = _mm256_add_pd(va, vb);
_mm256_storeu_pd(c + i, vc);
}
}
// ========== 矩阵乘法优化(AVX) ==========
void matrix_multiply_avx(const float* A, const float* B, float* C, int N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
__m256 sum = _mm256_setzero_ps();
for (int k = 0; k < N; k += 8) {
__m256 va = _mm256_loadu_ps(A + i * N + k);
__m256 vb = _mm256_loadu_ps(B + k * N + j);
sum = _mm256_add_ps(sum, _mm256_mul_ps(va, vb));
}
float result[8];
_mm256_storeu_ps(result, sum);
C[i * N + j] = result[0] + result[1] + result[2] + result[3] +
result[4] + result[5] + result[6] + result[7];
}
}
}
// ========== 自动向量化提示 ==========
void auto_vectorize() {
std::vector<float> a(1000), b(1000), c(1000);
#pragma omp simd
for (int i = 0; i < 1000; i++) {
c[i] = a[i] + b[i];
}
#pragma GCC ivdep
for (int i = 0; i < 1000; i++) {
c[i] = a[i] * b[i];
}
}
六、设计模式与架构
6.1 现代C++设计模式
#include <iostream>
#include <memory>
#include <functional>
#include <vector>
#include <map>
// ========== 策略模式(使用std::function) ==========
class Calculator {
private:
std::function<int(int, int)> strategy;
public:
void setStrategy(std::function<int(int, int)> s) {
strategy = s;
}
int execute(int a, int b) {
return strategy(a, b);
}
};
// ========== 观察者模式(使用信号槽) ==========
class Observable {
private:
std::vector<std::function<void(int)>> observers;
public:
void addObserver(std::function<void(int)> observer) {
observers.push_back(observer);
}
void notify(int value) {
for (auto& observer : observers) {
observer(value);
}
}
};
// ========== 访问者模式(使用std::variant) ==========
#include <variant>
struct Circle { double radius; };
struct Rectangle { double width, height; };
using Shape = std::variant<Circle, Rectangle>;
double area(const Shape& shape) {
return std::visit([](auto&& s) -> double {
using T = std::decay_t<decltype(s)>;
if constexpr (std::is_same_v<T, Circle>) {
return 3.14159 * s.radius * s.radius;
} else if constexpr (std::is_same_v<T, Rectangle>) {
return s.width * s.height;
}
return 0.0;
}, shape);
}
// ========== 工厂模式(使用注册表) ==========
class Product {
public:
virtual void use() = 0;
virtual ~Product() = default;
};
class ProductFactory {
private:
using Creator = std::function<std::unique_ptr<Product>()>;
std::map<std::string, Creator> creators;
public:
void registerCreator(const std::string& name, Creator creator) {
creators[name] = creator;
}
std::unique_ptr<Product> create(const std::string& name) {
auto it = creators.find(name);
if (it != creators.end()) {
return it->second();
}
return nullptr;
}
};
class ConcreteProduct : public Product {
public:
void use() override {
std::cout << "Using concrete product" << std::endl;
}
};
// ========== 建造者模式(使用链式调用) ==========
class Computer {
public:
std::string cpu;
int memory;
int storage;
std::string gpu;
class Builder {
private:
Computer computer;
public:
Builder& setCPU(const std::string& cpu) {
computer.cpu = cpu;
return *this;
}
Builder& setMemory(int memory) {
computer.memory = memory;
return *this;
}
Builder& setStorage(int storage) {
computer.storage = storage;
return *this;
}
Builder& setGPU(const std::string& gpu) {
computer.gpu = gpu;
return *this;
}
Computer build() {
return computer;
}
};
};
void design_patterns_demo() {
// 策略模式
Calculator calc;
calc.setStrategy([](int a, int b) { return a + b; });
std::cout << "Add: " << calc.execute(10, 5) << std::endl;
calc.setStrategy([](int a, int b) { return a * b; });
std::cout << "Multiply: " << calc.execute(10, 5) << std::endl;
// 观察者模式
Observable observable;
observable.addObserver([](int v) { std::cout << "Observer 1: " << v << std::endl; });
observable.addObserver([](int v) { std::cout << "Observer 2: " << v << std::endl; });
observable.notify(42);
// 访问者模式
Shape shape = Circle{5.0};
std::cout << "Circle area: " << area(shape) << std::endl;
shape = Rectangle{4.0, 6.0};
std::cout << "Rectangle area: " << area(shape) << std::endl;
// 建造者模式
Computer pc = Computer::Builder()
.setCPU("Intel i9")
.setMemory(32)
.setStorage(1024)
.setGPU("RTX 4090")
.build();
}
知识体系图谱
C++高阶开发
├── 模板元编程
│ ├── 编译期计算
│ ├── 类型萃取
│ ├── SFINAE
│ ├── 表达式模板
│ └── CRTP
├── 内存模型
│ ├── 内存顺序
│ ├── 原子操作
│ ├── 无锁数据结构
│ └── 内存屏障
├── 编译器内部
│ ├── 对象模型
│ ├── 虚函数实现
│ ├── RTTI机制
│ └── 异常处理
├── ABI与链接
│ ├── 名字修饰
│ ├── 符号可见性
│ ├── 二进制兼容性
│ └── 动态库
├── 性能优化
│ ├── 编译期优化
│ ├── SIMD向量化
│ ├── 分支预测
│ └── 缓存优化
└── 架构设计
├── 现代设计模式
├── 依赖注入
├── 接口隔离
└── 微服务架构
高阶开发者的标志是能够理解语言的底层实现,能够在编译期解决问题,能够设计高性能、高并发、高可靠性的系统。当你能够实现自己的智能指针、无锁数据结构、表达式模板库,能够理解虚函数表的布局,能够优化缓存未命中时,你已经成为了一名真正的C++专家。
来源:
https://app-a6nw7st4g741.appmiaoda.com/