当你已经掌握了C++的进阶知识,能够编写高效、安全的现代C++代码时,真正的挑战才刚刚开始。C++高阶开发要求你深入理解语言底层机制、掌握编译期编程、精通内存模型与并发、能够进行系统级性能调优、理解编译器实现原理。本文将系统梳理C++高阶开发的核心知识体系,涵盖模板元编程、类型萃取、内存模型、无锁编程、编译器内部机制、ABI与链接、性能极致优化、设计模式与架构等深度领域,助你完成从优秀开发者到系统级专家的跨越。
一、模板元编程
1.1 模板元编程基础
模板元编程(TMP)是在编译期执行的程序,它利用模板实例化机制进行编译期计算。
#include <iostream>
#include <type_traits>
// ========== 编译期阶乘 ==========
template<int N>
struct Factorial {
static constexpr int value = N * Factorial<N - 1>::value;
};
template<>
struct Factorial<0> {
static constexpr int value = 1;
};
// ========== 编译期斐波那契 ==========
template<int N>
struct Fibonacci {
static constexpr int value = Fibonacci<N - 1>::value + Fibonacci<N - 2>::value;
};
template<>
struct Fibonacci<0> {
static constexpr int value = 0;
};
template<>
struct Fibonacci<1> {
static constexpr int value = 1;
};
// ========== 编译期素数判断 ==========
template<int N, int D>
struct IsPrimeHelper {
static constexpr bool value = (N % D != 0) && IsPrimeHelper<N, D - 1>::value;
};
template<int N>
struct IsPrimeHelper<N, 1> {
static constexpr bool value = true;
};
template<int N>
struct IsPrime {
static constexpr bool value = IsPrimeHelper<N, N / 2>::value;
};
template<>
struct IsPrime<1> {
static constexpr bool value = false;
};
template<>
struct IsPrime<2> {
static constexpr bool value = true;
};
// ========== 编译期列表操作 ==========
template<int... Values>
struct IntList {};
// 计算列表长度
template<typename>
struct Length;
template<int First, int... Rest>
struct Length<IntList<First, Rest...>> {
static constexpr int value = 1 + Length<IntList<Rest...>>::value;
};
template<>
struct Length<IntList<>> {
static constexpr int value = 0;
};
// 求和
template<typename>
struct Sum;
template<int First, int... Rest>
struct Sum<IntList<First, Rest...>> {
static constexpr int value = First + Sum<IntList<Rest...>>::value;
};
template<>
struct Sum<IntList<>> {
static constexpr int value = 0;
};
// 列表连接
template<typename, typename>
struct Concat;
template<int... A, int... B>
struct Concat<IntList<A...>, IntList<B...>> {
using type = IntList<A..., B...>;
};
void tmp_basics() {
std::cout << "5! = " << Factorial<5>::value << std::endl;
std::cout << "Fibonacci(10) = " << Fibonacci<10>::value << std::endl;
std::cout << "IsPrime(17) = " << IsPrime<17>::value << std::endl;
std::cout << "IsPrime(100) = " << IsPrime<100>::value << std::endl;
using List = IntList<1, 2, 3, 4, 5>;
std::cout << "Length = " << Length<List>::value << std::endl;
std::cout << "Sum = " << Sum<List>::value << std::endl;
using ConcatList = Concat<IntList<1, 2, 3>, IntList<4, 5, 6>>::type;
std::cout << "Concat length = " << Length<ConcatList>::value << std::endl;
}
1.2 类型萃取与SFINAE
#include <iostream>
#include <type_traits>
#include <vector>
#include <list>
// ========== 类型萃取基础 ==========
// 判断是否为指针
template<typename T>
struct IsPointer {
static constexpr bool value = false;
};
template<typename T>
struct IsPointer<T*> {
static constexpr bool value = true;
};
// 判断是否为引用
template<typename T>
struct IsReference {
static constexpr bool value = false;
};
template<typename T>
struct IsReference<T&> {
static constexpr bool value = true;
};
template<typename T>
struct IsReference<T&&> {
static constexpr bool value = true;
};
// 移除引用
template<typename T>
struct RemoveReference {
using type = T;
};
template<typename T>
struct RemoveReference<T&> {
using type = T;
};
template<typename T>
struct RemoveReference<T&&> {
using type = T;
};
// 添加const
template<typename T>
struct AddConst {
using type = const T;
};
// ========== 高级类型萃取 ==========
// 判断是否可调用
template<typename, typename = void>
struct IsCallable : std::false_type {};
template<typename F, typename... Args>
struct IsCallable<F(Args...),
std::void_t<decltype(std::declval<F>()(std::declval<Args>()...))>>
: std::true_type {};
// 函数返回值类型
template<typename F, typename... Args>
struct ReturnType;
template<typename F, typename... Args>
struct ReturnType<F(Args...)> {
using type = decltype(std::declval<F>()(std::declval<Args>()...));
};
// ========== SFINAE ==========
// Substitution Failure Is Not An Error
// enable_if:根据条件启用或禁用函数
template<typename T>
typename std::enable_if<std::is_integral<T>::value, T>::type
half(T x) {
return x / 2;
}
template<typename T>
typename std::enable_if<!std::is_integral<T>::value, T>::type
half(T x) {
return x / 2.0;
}
// 检测类型是否有成员函数
template<typename, typename = void>
struct HasBegin : std::false_type {};
template<typename T>
struct HasBegin<T, std::void_t<decltype(std::declval<T>().begin())>>
: std::true_type {};
// 容器类型判断
template<typename T>
struct IsContainer : std::false_type {};
template<typename T, typename Alloc>
struct IsContainer<std::vector<T, Alloc>> : std::true_type {};
template<typename T, typename Alloc>
struct IsContainer<std::list<T, Alloc>> : std::true_type {};
// ========== void_t(C++17) ==========
// void_t用于检测表达式有效性
template<typename...>
using void_t = void;
// 检测是否有size_type
template<typename, typename = void>
struct HasSizeType : std::false_type {};
template<typename T>
struct HasSizeType<T, void_t<typename T::size_type>>
: std::true_type {};
void type_traits_demo() {
std::cout << std::boolalpha;
std::cout << "IsPointer<int>: " << IsPointer<int>::value << std::endl;
std::cout << "IsPointer<int*>: " << IsPointer<int*>::value << std::endl;
std::cout << "half(10): " << half(10) << std::endl;
std::cout << "half(10.5): " << half(10.5) << std::endl;
std::cout << "HasBegin<vector>: " << HasBegin<std::vector<int>>::value << std::endl;
std::cout << "HasBegin<int>: " << HasBegin<int>::value << std::endl;
}
1.3 表达式模板与编译期优化
#include <iostream>
#include <vector>
#include <cmath>
// ========== 表达式模板 ==========
// 用于延迟计算和消除临时对象
// 表达式节点基类
template<typename Derived>
struct Expression {
Derived& derived() { return static_cast<Derived&>(*this); }
const Derived& derived() const { return static_cast<const Derived&>(*this); }
double operator[](size_t i) const {
return derived()[i];
}
size_t size() const {
return derived().size();
}
};
// 数值节点
struct Number : Expression<Number> {
double value;
Number(double v) : value(v) {}
double operator[](size_t) const { return value; }
size_t size() const { return 0; }
};
// 向量节点
struct Vector : Expression<Vector> {
std::vector<double> data;
Vector(size_t n) : data(n) {}
Vector(const std::vector<double>& v) : data(v) {}
double operator[](size_t i) const { return data[i]; }
size_t size() const { return data.size(); }
};
// 加法节点
template<typename L, typename R>
struct Add : Expression<Add<L, R>> {
L lhs;
R rhs;
Add(const L& l, const R& r) : lhs(l), rhs(r) {}
double operator[](size_t i) const {
return lhs[i] + rhs[i];
}
size_t size() const {
return std::max(lhs.size(), rhs.size());
}
};
// 乘法节点
template<typename L, typename R>
struct Mul : Expression<Mul<L, R>> {
L lhs;
R rhs;
Mul(const L& l, const R& r) : lhs(l), rhs(r) {}
double operator[](size_t i) const {
return lhs[i] * rhs[i];
}
size_t size() const {
return std::max(lhs.size(), rhs.size());
}
};
// 操作符重载
template<typename L, typename R>
Add<L, R> operator+(const Expression<L>& l, const Expression<R>& r) {
return Add<L, R>(l.derived(), r.derived());
}
template<typename L, typename R>
Mul<L, R> operator*(const Expression<L>& l, const Expression<R>& r) {
return Mul<L, R>(l.derived(), r.derived());
}
// 赋值操作
template<typename T>
void operator=(std::vector<double>& vec, const Expression<T>& expr) {
vec.resize(expr.size());
for (size_t i = 0; i < expr.size(); i++) {
vec[i] = expr[i];
}
}
void expression_template_demo() {
Vector a(10), b(10);
for (size_t i = 0; i < 10; i++) {
a.data[i] = i;
b.data[i] = i * 2;
}
// 表达式模板:不会创建临时对象
// 编译为:c[i] = a[i] + a[i] * b[i]
std::vector<double> c;
c = a + a * b;
for (size_t i = 0; i < c.size(); i++) {
std::cout << c[i] << " ";
}
std::cout << std::endl;
}
1.4 CRTP(奇异递归模板模式)
#include <iostream>
#include <memory>
// ========== CRTP基础 ==========
// 静态多态(编译期多态)
template<typename Derived>
class Base {
public:
void interface() {
static_cast<Derived*>(this)->implementation();
}
void common() {
std::cout << "Base common" << std::endl;
static_cast<Derived*>(this)->specific();
}
};
class Derived1 : public Base<Derived1> {
public:
void implementation() {
std::cout << "Derived1 implementation" << std::endl;
}
void specific() {
std::cout << "Derived1 specific" << std::endl;
}
};
class Derived2 : public Base<Derived2> {
public:
void implementation() {
std::cout << "Derived2 implementation" << std::endl;
}
void specific() {
std::cout << "Derived2 specific" << std::endl;
}
};
// ========== 对象计数器 ==========
template<typename T>
class ObjectCounter {
private:
static inline int count = 0;
protected:
ObjectCounter() { ++count; }
~ObjectCounter() { --count; }
public:
static int getCount() { return count; }
};
class Widget : public ObjectCounter<Widget> {
public:
Widget() : ObjectCounter() {}
};
// ========== 运算符重载统一实现 ==========
template<typename Derived>
class EqualityComparable {
public:
friend bool operator!=(const Derived& lhs, const Derived& rhs) {
return !(lhs == rhs);
}
};
class Point : public EqualityComparable<Point> {
int x, y;
public:
Point(int x, int y) : x(x), y(y) {}
bool operator==(const Point& other) const {
return x == other.x && y == other.y;
}
};
// ========== 克隆模式 ==========
template<typename Derived>
class Clonable {
public:
std::unique_ptr<Derived> clone() const {
return std::unique_ptr<Derived>(static_cast<const Derived*>(this)->cloneImpl());
}
protected:
~Clonable() = default;
// 禁用拷贝
Clonable() = default;
Clonable(const Clonable&) = delete;
Clonable& operator=(const Clonable&) = delete;
};
class Shape : public Clonable<Shape> {
public:
virtual void draw() const = 0;
virtual ~Shape() = default;
protected:
virtual Shape* cloneImpl() const = 0;
};
class Circle : public Shape {
double radius;
public:
Circle(double r) : radius(r) {}
void draw() const override {
std::cout << "Circle with radius " << radius << std::endl;
}
protected:
Shape* cloneImpl() const override {
return new Circle(*this);
}
};
class Rectangle : public Shape {
double w, h;
public:
Rectangle(double width, double height) : w(width), h(height) {}
void draw() const override {
std::cout << "Rectangle " << w << "x" << h << std::endl;
}
protected:
Shape* cloneImpl() const override {
return new Rectangle(*this);
}
};
void crtp_demo() {
Derived1 d1;
Derived2 d2;
d1.interface();
d2.interface();
d1.common();
d2.common();
Widget w1, w2, w3;
std::cout << "Widget count: " << Widget::getCount() << std::endl;
Point p1(1, 2), p2(1, 2), p3(3, 4);
std::cout << "p1 == p2: " << (p1 == p2) << std::endl;
std::cout << "p1 != p2: " << (p1 != p2) << std::endl;
std::cout << "p1 != p3: " << (p1 != p3) << std::endl;
std::unique_ptr<Shape> shape1 = std::make_unique<Circle>(5.0);
auto shape2 = shape1->clone();
shape1->draw();
shape2->draw();
}
二、C++内存模型与并发
2.1 C++内存模型深入
#include <iostream>
#include <atomic>
#include <thread>
#include <vector>
// ========== 内存顺序 ==========
/*
* memory_order_relaxed: 松散顺序,只保证原子性
* memory_order_acquire: 获取操作,之后的读写不能重排到此之前
* memory_order_release: 释放操作,之前的读写不能重排到此之后
* memory_order_acq_rel: 同时具有acquire和release语义
* memory_order_seq_cst: 顺序一致性(默认)
*/
// ========== 无锁队列(使用内存顺序优化) ==========
template<typename T>
class LockFreeQueue {
private:
struct Node {
T data;
std::atomic<Node*> next;
Node(const T& value) : data(value), next(nullptr) {}
};
std::atomic<Node*> head;
std::atomic<Node*> tail;
public:
LockFreeQueue() {
Node* dummy = new Node(T());
head.store(dummy, std::memory_order_relaxed);
tail.store(dummy, std::memory_order_relaxed);
}
void push(const T& value) {
Node* node = new Node(value);
Node* old_tail = tail.load(std::memory_order_acquire);
Node* expected = nullptr;
while (!old_tail->next.compare_exchange_weak(expected, node,
std::memory_order_release,
std::memory_order_relaxed)) {
expected = nullptr;
old_tail = tail.load(std::memory_order_acquire);
}
tail.compare_exchange_strong(old_tail, node,
std::memory_order_release,
std::memory_order_relaxed);
}
bool pop(T& result) {
Node* old_head = head.load(std::memory_order_acquire);
while (old_head != tail.load(std::memory_order_acquire)) {
Node* next = old_head->next.load(std::memory_order_acquire);
if (head.compare_exchange_weak(old_head, next,
std::memory_order_release,
std::memory_order_relaxed)) {
result = next->data;
delete old_head;
return true;
}
old_head = head.load(std::memory_order_acquire);
}
return false;
}
~LockFreeQueue() {
while (pop(T())) {}
delete head.load();
}
};
// ========== 双检锁与内存顺序 ==========
class Singleton {
private:
static std::atomic<Singleton*> instance;
static std::mutex mtx;
Singleton() = default;
public:
static Singleton* getInstance() {
Singleton* ptr = instance.load(std::memory_order_acquire);
if (!ptr) {
std::lock_guard<std::mutex> lock(mtx);
ptr = instance.load(std::memory_order_relaxed);
if (!ptr) {
ptr = new Singleton();
instance.store(ptr, std::memory_order_release);
}
}
return ptr;
}
};
std::atomic<Singleton*> Singleton::instance{nullptr};
std::mutex Singleton::mtx;
// ========== 发布-订阅模式的内存屏障 ==========
std::atomic<bool> ready{false};
std::atomic<int> data{0};
void producer() {
data.store(42, std::memory_order_relaxed);
ready.store(true, std::memory_order_release); // 释放屏障
}
void consumer() {
while (!ready.load(std::memory_order_acquire)) { // 获取屏障
std::this_thread::yield();
}
std::cout << "Data: " << data.load(std::memory_order_relaxed) << std::endl;
}
2.2 无锁数据结构实现
#include <atomic>
#include <memory>
#include <iostream>
// ========== 无锁栈(Treiber Stack) ==========
template<typename T>
class LockFreeStack {
private:
struct Node {
T data;
std::atomic<Node*> next;
Node(const T& value) : data(value), next(nullptr) {}
};
std::atomic<Node*> head;
public:
LockFreeStack() : head(nullptr) {}
void push(const T& value) {
Node* node = new Node(value);
node->next = head.load(std::memory_order_relaxed);
while (!head.compare_exchange_weak(node->next, node,
std::memory_order_release,
std::memory_order_relaxed)) {}
}
bool pop(T& result) {
Node* old_head = head.load(std::memory_order_acquire);
while (old_head && !head.compare_exchange_weak(old_head, old_head->next,
std::memory_order_release,
std::memory_order_relaxed)) {}
if (!old_head) return false;
result = old_head->data;
delete old_head;
return true;
}
};
// ========== 无锁哈希表 ==========
template<typename Key, typename Value>
class LockFreeHashMap {
private:
struct Bucket {
std::atomic<Bucket*> next;
Key key;
Value value;
Bucket(const Key& k, const Value& v) : next(nullptr), key(k), value(v) {}
};
std::vector<std::atomic<Bucket*>> buckets;
size_t size;
size_t hash(const Key& key) const {
return std::hash<Key>{}(key) % size;
}
public:
LockFreeHashMap(size_t sz) : size(sz), buckets(sz) {
for (auto& bucket : buckets) {
bucket.store(nullptr, std::memory_order_relaxed);
}
}
void insert(const Key& key, const Value& value) {
size_t idx = hash(key);
Bucket* new_bucket = new Bucket(key, value);
Bucket* old_head = buckets[idx].load(std::memory_order_relaxed);
new_bucket->next.store(old_head, std::memory_order_relaxed);
while (!buckets[idx].compare_exchange_weak(old_head, new_bucket,
std::memory_order_release,
std::memory_order_relaxed)) {
new_bucket->next.store(old_head, std::memory_order_relaxed);
}
}
bool find(const Key& key, Value& result) const {
size_t idx = hash(key);
Bucket* current = buckets[idx].load(std::memory_order_acquire);
while (current) {
if (current->key == key) {
result = current->value;
return true;
}
current = current->next.load(std::memory_order_acquire);
}
return false;
}
};
2.3 std::atomic与内存屏障
#include <atomic>
#include <thread>
#include <iostream>
// ========== 原子操作高级用法 ==========
class AtomicCounter {
private:
std::atomic<int> value;
public:
AtomicCounter() : value(0) {}
void increment() {
// fetch_add返回旧值
int old = value.fetch_add(1, std::memory_order_acq_rel);
// 或使用 ++value;
}
int get() const {
return value.load(std::memory_order_acquire);
}
// 比较并交换
bool compare_and_set(int expected, int desired) {
return value.compare_exchange_strong(expected, desired,
std::memory_order_acq_rel,
std::memory_order_relaxed);
}
// 读-改-写
int add_and_fetch(int delta) {
return value.fetch_add(delta, std::memory_order_acq_rel) + delta;
}
};
// ========== 自旋锁实现 ==========
class SpinLock {
private:
std::atomic<bool> flag;
public:
SpinLock() : flag(false) {}
void lock() {
bool expected = false;
while (!flag.compare_exchange_weak(expected, true,
std::memory_order_acquire,
std::memory_order_relaxed)) {
expected = false;
// 可选:暂停指令
#if defined(__x86_64__)
__asm__ volatile("pause");
#endif
}
}
void unlock() {
flag.store(false, std::memory_order_release);
}
};
// ========== 读写锁实现(基于原子操作) ==========
class AtomicRWLock {
private:
std::atomic<int> readers;
std::atomic<bool> writer;
public:
AtomicRWLock() : readers(0), writer(false) {}
void read_lock() {
while (true) {
while (writer.load(std::memory_order_acquire)) {
std::this_thread::yield();
}
readers.fetch_add(1, std::memory_order_acquire);
if (!writer.load(std::memory_order_relaxed)) {
break;
}
readers.fetch_sub(1, std::memory_order_release);
}
}
void read_unlock() {
readers.fetch_sub(1, std::memory_order_release);
}
void write_lock() {
bool expected = false;
while (!writer.compare_exchange_weak(expected, true,
std::memory_order_acquire,
std::memory_order_relaxed)) {
expected = false;
}
while (readers.load(std::memory_order_acquire) != 0) {
std::this_thread::yield();
}
}
void write_unlock() {
writer.store(false, std::memory_order_release);
}
};
三、编译器内部机制
3.1 对象模型与虚函数实现
#include <iostream>
#include <cstdint>
// ========== 对象内存布局 ==========
class Base {
public:
int a;
virtual void func1() { std::cout << "Base::func1" << std::endl; }
virtual void func2() { std::cout << "Base::func2" << std::endl; }
};
class Derived : public Base {
public:
int b;
void func1() override { std::cout << "Derived::func1" << std::endl; }
virtual void func3() { std::cout << "Derived::func3" << std::endl; }
};
void object_layout_demo() {
Base b;
Derived d;
// 查看对象大小
std::cout << "sizeof(Base): " << sizeof(Base) << std::endl;
std::cout << "sizeof(Derived): " << sizeof(Derived) << std::endl;
// 虚函数表指针位置
uintptr_t* vptr_base = reinterpret_cast<uintptr_t*>(&b);
uintptr_t* vptr_derived = reinterpret_cast<uintptr_t*>(&d);
std::cout << "Base vptr: " << vptr_base[0] << std::endl;
std::cout << "Derived vptr: " << vptr_derived[0] << std::endl;
}
// ========== 手动调用虚函数 ==========
void manual_virtual_call() {
Base* ptr = new Derived();
// 获取虚函数表
uintptr_t* vptr = *reinterpret_cast<uintptr_t**>(ptr);
// 调用第一个虚函数
using FuncPtr = void(*)();
FuncPtr func = reinterpret_cast<FuncPtr>(vptr[0]);
func();
// 调用第二个虚函数
func = reinterpret_cast<FuncPtr>(vptr[1]);
func();
delete ptr;
}
// ========== 多继承下的虚函数 ==========
class Base1 {
public:
virtual void f1() { std::cout << "Base1::f1" << std::endl; }
virtual void f2() { std::cout << "Base1::f2" << std::endl; }
};
class Base2 {
public:
virtual void g1() { std::cout << "Base2::g1" << std::endl; }
virtual void g2() { std::cout << "Base2::g2" << std::endl; }
};
class MultiDerived : public Base1, public Base2 {
public:
void f1() override { std::cout << "MultiDerived::f1" << std::endl; }
void g1() override { std::cout << "MultiDerived::g1" << std::endl; }
virtual void h1() { std::cout << "MultiDerived::h1" << std::endl; }
};
void multi_inheritance_layout() {
MultiDerived d;
Base1* b1 = &d;
Base2* b2 = &d;
// 不同基类指针指向不同偏移
std::cout << "b1: " << b1 << std::endl;
std::cout << "b2: " << b2 << std::endl;
std::cout << "&d: " << &d << std::endl;
// 调整this指针
b1->f1(); // this指向Base1部分
b2->g1(); // this指向Base2部分(需要调整)
}
3.2 RTTI与dynamic_cast实现
#include <iostream>
#include <typeinfo>
// ========== RTTI原理 ==========
class RTTIBase {
public:
virtual ~RTTIBase() = default;
virtual void dummy() {}
};
class RTTIDerived : public RTTIBase {};
void rtti_demo() {
RTTIBase* base = new RTTIDerived();
// typeid获取类型信息
std::cout << "typeid(base): " << typeid(base).name() << std::endl;
std::cout << "typeid(*base): " << typeid(*base).name() << std::endl;
// dynamic_cast(需要虚函数)
RTTIDerived* derived = dynamic_cast<RTTIDerived*>(base);
if (derived) {
std::cout << "dynamic_cast success" << std::endl;
}
// 错误的转换
RTTIBase* base2 = new RTTIBase();
RTTIDerived* derived2 = dynamic_cast<RTTIDerived*>(base2);
if (!derived2) {
std::cout << "dynamic_cast failed" << std::endl;
}
delete base;
delete base2;
}
// ========== 模拟dynamic_cast ==========
// 使用虚函数获取类型ID
class TypeAware {
public:
virtual int getTypeId() const = 0;
virtual ~TypeAware() = default;
};
class Type1 : public TypeAware {
public:
int getTypeId() const override { return 1; }
};
class Type2 : public TypeAware {
public:
int getTypeId() const override { return 2; }
};
template<typename Target>
Target* my_dynamic_cast(TypeAware* ptr) {
if (ptr && ptr->getTypeId() == Target::getStaticTypeId()) {
return static_cast<Target*>(ptr);
}
return nullptr;
}
3.3 异常处理实现机制
#include <iostream>
#include <exception>
#include <csetjmp>
// ========== 异常处理开销分析 ==========
// 零成本异常处理:不抛出异常时无开销
// 抛出异常时使用表驱动查找
class ExceptionDemo {
public:
void mightThrow() {
if (rand() % 2) {
throw std::runtime_error("Random error");
}
}
void safeCall() {
try {
mightThrow();
} catch (const std::exception& e) {
std::cout << "Caught: " << e.what() << std::endl;
}
}
};
// ========== 异常安全级别 ==========
// 基本保证:不泄漏资源
// 强保证:事务性操作
// 不抛出保证:noexcept
class StrongGuarantee {
private:
std::vector<int> data;
public:
// 强保证:使用copy-and-swap
void addElement(int value) {
std::vector<int> temp = data; // 副本
temp.push_back(value);
data.swap(temp); // 不抛出
}
// 不抛出保证
void swap(StrongGuarantee& other) noexcept {
data.swap(other.data);
}
};
// ========== 自定义异常类 ==========
class MyException : public std::exception {
private:
std::string message;
int errorCode;
public:
MyException(const std::string& msg, int code)
: message(msg), errorCode(code) {}
const char* what() const noexcept override {
return message.c_str();
}
int getErrorCode() const { return errorCode; }
};
void custom_exception_demo() {
try {
throw MyException("Custom error", 1001);
} catch (const MyException& e) {
std::cout << "Error: " << e.what()
<< ", Code: " << e.getErrorCode() << std::endl;
}
}