constexpr 讓編譯器在編譯期計算表達式,可用於數組大小、模板參數等要求編譯期常量的上下文。
return 語句(C++14 放寬)constexpr int get() { return 10; }
int arr[get()]; // 合法:編譯期常量
constexpr int a = get(); // a 是編譯期常量
int b = get(); // b 是運行期變量
// 常量構造函數與字面值類型
struct Date {
constexpr Date(int y, int m, int d) : year(y), month(m), day(d) {}
constexpr int GetYear() const { return year; }
int year, month, day;
};
constexpr Date PRC{1949, 10, 1}; // 編譯期構造
constexpr int m = PRC.GetMonth(); // 10
模板參數包 typename... Elements 與函數參數包 T... args 配合 sizeof...(Args)、展開運算符 ... 實現任意參數個數的泛型編程。
templateclass tuple; // std::tuple 即此類 tuple t1; // 任意類型、任意個數 template void f(T... args); // 參數包 // 遞歸展開典型模式 void print() {} template void print(Head h, Tail... t) { cout << h << ' '; print(t...); }
std::atomic 提供無鎖線程同步。內存序控制編譯器/CPU 重排序:
| memory_order | 語義 |
|---|---|
| relaxed | 無順序保證,僅保證原子性 |
| acquire | 後續讀操作不重排到此前 |
| release | 前序寫操作不重排到此後 |
| acq_rel | 同時具備 acquire/release |
| consume | 弱化 acquire,僅保證相關數據依賴 |
| seq_cst | 順序一致性,最強,默認值 |
// 生產者 a.store(1, memory_order_relaxed); b.store(2, memory_order_release); // 保證 a=1 可見 // 消費者 while (b.load(memory_order_acquire) != 2); // 獲取語義 assert(a.load(memory_order_relaxed) == 1); // 必然成立
thread_local (C++11) / __thread (GCC 擴展) 讓每個線程擁有獨立副本:
thread_local int tls_int = 0; // 基本類型直接用 thread_local std::string* tls_str_ptr; // 類類型用指針,避免構造/析構順序問題
| 函數 | 析構函數 | atexit 處理器 | 信號 | 用途 |
|---|---|---|---|---|
| return / exit | ✓ | ✓ (逆序) | 無 | 正常退出 |
| quick_exit | ✗ | ✗ | 無 | 快速退出,配合 at_quick_exit |
| abort / terminate | ✗ | ✗ | SIGABRT | 異常終止,不清理 |
constexpr 替代宏常量,獲得類型安全與作用域seq_cst 通常足夠;性能敏感處再微調內存序thread_local 替代 __thread,標準化且支援類類型