C++核心準(zhǔn)則C.181:避免使用"暴露的"聯(lián)合體

C.181: Avoid "naked"?unions
C.181:避免使用"暴露的"聯(lián)合體
Reason(原因)
A?naked union?is a union without an associated indicator which member (if any) it holds, so that the programmer has to keep track. Naked unions are a source of type errors.
暴露的聯(lián)合體指的是不包含用來表示哪個(gè)(如果存在的話)成員有效的標(biāo)志的聯(lián)合體,程序員必須對數(shù)據(jù)流保持跟蹤。暴露狀態(tài)的聯(lián)合體是錯(cuò)誤的源頭之一。
Example, bad(反面示例)
union Value {
int x;
double d;
};
Value v;
v.d = 987.654; // v holds a double
So far, so good, but we can easily misuse the?union:
到目前為止還好,但是我們會(huì)很容易地錯(cuò)誤使用這個(gè)聯(lián)合體:
cout << v.x << '\n'; // BAD, undefined behavior: v holds a double, but we read it as an int
Note that the type error happened without any explicit cast. When we tested that program the last value printed was?1683627180?which is the integer value for the bit pattern for?987.654. What we have here is an "invisible" type error that happens to give a result that could easily look innocent.
注意類型錯(cuò)誤是在沒有任何顯式類型轉(zhuǎn)換的情況下發(fā)生的。但我們測試這段程序的時(shí)候,輸出的最后一個(gè)值是1863627180,它是987.654的二進(jìn)制對應(yīng)的整數(shù)值。我們在這里遇到的是一個(gè)"不可見"類型錯(cuò)誤,它恰巧給出一個(gè)很容易被判斷為沒有問題的結(jié)果。
And, talking about "invisible", this code produced no output:
另外,談到"不可見",下面的代碼不會(huì)產(chǎn)生輸出:
v.x = 123;
cout << v.d << '\n'; // BAD: undefined behaviorAlternative(可選項(xiàng))
Wrap a?union?in a class together with a type field.
將聯(lián)合體和一個(gè)類型字段封裝為一個(gè)類。
The C++17?variant?type (found in?
C++17的variant類型(可以在
variant v;
v = 123; // v holds an int
int x = get(v);
v = 123.456; // v holds a double
w = get(v); Enforcement(實(shí)施建議)
???
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c181-avoid-naked-unions
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
