| 成員型別 | C++98/03 | C++11 起 | 說明 |
| POD 類型 (int, float, struct 無建構子) | ✅ | ✅ | 完全支援 |
| 含使用者定義建構子/解構子/複製/移動 | ❌ 編譯錯誤 | ❌ 編譯錯誤 | 生命週期管理衝突 |
| 含虛函數/虛基類 | ❌ | ❌ | 虛表指標衝突 |
| 非靜態資料成員初始化 | ❌ | ✅ (C++11) | 僅限字面類型 |
| 標準佈局類別 | ❌ | ✅ (C++11) | 無虛函數、單一存取控制、無基類 |
為什麼禁止建構子/解構子?
Union 不知哪個成員處於作用中,無法自動呼叫正確的建構子/解構子。若允許:
- 建構時呼叫哪個建構子?全部呼叫會多重初始化同一記憶體;不呼叫則未初始化
- 解構時呼叫哪個解構子?可能導致資源重複釋放或洩漏
- 指派運算子同理
因此標準規定:Union 只負責配置記憶體,不負責物件生命週期。程式設計師必須手動管理(Placement new / 顯式呼叫解構子)。
現代 C++ 正確用法:手動生命週期管理
#include
#include
#include // placement new
#include // std::move
// 安全的 Variant 實作雛形
class SafeVariant {
// 聯合體:只能放置 POD 或標準佈局類型
union Storage {
int intVal;
double doubleVal;
char strBuffer[32]; // 固定緩衝區模擬 string
Storage() {} // 無操作
~Storage() {} // 無操作
} storage;
enum class Type { INT, DOUBLE, STRING, EMPTY } type = Type::EMPTY;
public:
SafeVariant() = default;
~SafeVariant() { destroy(); }
// 複製/移動語意
SafeVariant(const SafeVariant& other) { copyFrom(other); }
SafeVariant(SafeVariant&& other) noexcept { moveFrom(std::move(other)); }
SafeVariant& operator=(const SafeVariant& other) {
if (this != &other) { destroy(); copyFrom(other); } return *this;
}
SafeVariant& operator=(SafeVariant&& other) noexcept {
if (this != &other) { destroy(); moveFrom(std::move(other)); } return *this;
}
// 設值
void setInt(int v) { destroy(); new(&storage.intVal) int(v); type = Type::INT; }
void setDouble(double v) { destroy(); new(&storage.doubleVal) double(v); type = Type::DOUBLE; }
void setString(const char* v) {
destroy();
std::snprintf(storage.strBuffer, sizeof(storage.strBuffer), "%s", v);
type = Type::STRING;
}
// 取值
int getInt() const {
if (type != Type::INT) throw std::runtime_error("Not an int");
return storage.intVal;
}
// ... 其他 getter
private:
void destroy() {
switch (type) {
case Type::INT: storage.intVal.~int(); break; // 基本型別解構子無操作,但保持形式
case Type::DOUBLE: storage.doubleVal.~double(); break;
case Type::STRING: /* strBuffer 無需解構 */ break;
default: break;
}
type = Type::EMPTY;
}
void copyFrom(const SafeVariant& other) {
type = other.type;
switch (type) {
case Type::INT: new(&storage.intVal) int(other.storage.intVal); break;
case Type::DOUBLE: new(&storage.doubleVal) double(other.storage.doubleVal); break;
case Type::STRING: std::snprintf(storage.strBuffer, sizeof(storage.strBuffer), "%s", other.storage.strBuffer); break;
default: break;
}
}
void moveFrom(SafeVariant&& other) {
copyFrom(other); // 簡化:基本型別移動即複製
other.destroy();
}
};
C++17 std::variant:標準化的類型安全 Union
現代 C++ 應優先使用 std::variant(定義於 <variant>),它是類型安全的 tagged union:
#include
#include
#include
using Value = std::variant;
void process(const Value& v) {
// 方式 1:std::visit (推薦,編譯期檢查完整性)
std::visit([](auto&& arg) {
using T = std::decay_t;
if constexpr (std::is_same_v) {
std::cout << "int: " << arg << '\n';
} else if constexpr (std::is_same_v) {
std::cout << "double: " << arg << '\n';
} else if constexpr (std::is_same_v) {
std::cout << "string: " << arg << '\n';
}
}, v);
// 方式 2:std::get / std::get_if
if (auto p = std::get_if(&v)) {
std::cout << "get_if int: " << *p << '\n';
}
// 方式 3:index() 判斷當前類型
std::cout << "Type index: " << v.index() << '\n'; // 0=int, 1=double, 2=string
}
int main() {
Value v1 = 42;
Value v2 = 3.14;
Value v3 = "Hello Variant";
process(v1);
process(v2);
process(v3);
// 安全轉換
try {
int i = std::get(v2); // 拋出 bad_variant_access
} catch (const std::bad_variant_access&) {
std::cout << "Type mismatch caught!\n";
}
}
經典用法模式:型別雙關
1. 重新命名/別名
struct Vec4 {
union {
struct { float x, y, z, w; };
struct { float r, g, b, a; };
float data[4];
};
float& operator[](size_t i) { return data[i]; }
const float& operator[](size_t i) const { return data[i]; }
};
// 用法:v.x, v.r, v[0] 指向同一記憶體
2. 壓縮/標籤聯合
struct CompressedPair {
// 利用指標低位對齊位存儲標籤(假設 8 位元組對齊,低 3 位可用)
union {
struct { void* ptr; };
struct { uintptr_t taggedPtr; };
};
bool isInt() const { return (taggedPtr & 1) != 0; }
int getInt() const { return static_cast(taggedPtr >> 1); }
void* getPtr() const { return reinterpret_cast(taggedPtr & ~0x7); }
};
3. 網路封包解析
#pragma pack(push, 1)
struct PacketHeader {
uint16_t magic;
uint16_t version;
uint32_t payloadLen;
uint32_t checksum;
};
#pragma pack(pop)
union PacketView {
PacketHeader header;
char raw[sizeof(PacketHeader)];
// 安全存取:檢查 magic、版本、校驗和
bool isValid() const {
return header.magic == 0xCAFE && header.version == 1;
}
};
效能與記憶體考量
| 指標 | Union | std::variant |
| 記憶體大小 | max(sizeof(members)) | max(sizeof(members)) + sizeof(tag) (通常 1-4 位元組) |
| 存取速度 | 直接存取,零開銷 | 需檢查 tag,極微小開銷 |
| 類型安全 | 無(程式設計師負責) | 完整(編譯期+執行期) |
| 建構/解構 | 手動管理 | 自動管理 |
| 適用場景 | 極致效能、硬體映射、C 相容 | 一般業務邏輯、類型安全優先 |
總結
Union 是 C++ 底層記憶體操作的利器,但充滿陷阱。現代 C++ 開發:
- 優先使用
std::variant 獲得類型安全
- 需要零開銷、硬體映射、C 相容時才用原生
union
- 若用原生 union,成員限制為 POD/標準佈局,手動管理生命週期
- 永遠不要在 union 放置含虛函數、非平凡建構子的類型
copyright ©
萬盛學電腦網 all rights reserved