首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

C++11 核心特性深度解析:constexpr、變長模板、原子操作與線程局部存儲

     編輯:C++ 入門

1. constexpr:編譯期常量與函數

constexpr 讓編譯器在編譯期計算表達式,可用於數組大小、模板參數等要求編譯期常量的上下文。

函數限制

  • 函數體僅包含單一 return 語句(C++14 放寬)
  • 必須有返回值,不能是 void
  • 使用前必須定義
  • 返回表達式不能依賴非常量全局數據或非 constexpr 函數

示例

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

2. 變長模板

模板參數包 typename... Elements 與函數參數包 T... args 配合 sizeof...(Args)、展開運算符 ... 實現任意參數個數的泛型編程。

template class tuple;  // std::tuple 即此類
tuple t1;                // 任意類型、任意個數

template void f(T... args);   // 參數包
// 遞歸展開典型模式
void print() {}
template
void print(Head h, Tail... t) { cout << h << ' '; print(t...); }

3. 原子類型與內存序

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); // 必然成立

4. 線程局部存儲

thread_local (C++11) / __thread (GCC 擴展) 讓每個線程擁有獨立副本:

thread_local int tls_int = 0;           // 基本類型直接用
thread_local std::string* tls_str_ptr;  // 類類型用指針,避免構造/析構順序問題

5. 程序退出方式對比

函數析構函數atexit 處理器信號用途
return / exit✓✓ (逆序)無正常退出
quick_exit✗✗無快速退出,配合 at_quick_exit
abort / terminate✗✗SIGABRT異常終止,不清理

工程建議

  • 優先使用 constexpr 替代宏常量,獲得類型安全與作用域
  • 變長模板配合折疊表達式 (C++17) 大幅簡化元編程
  • 原子操作默認 seq_cst 通常足夠;性能敏感處再微調內存序
  • thread_local 替代 __thread,標準化且支援類類型
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved