C++核心準(zhǔn)則C.180:使用聯(lián)合體節(jié)約內(nèi)存

C.180: Use?unions to save memory
C.180:使用聯(lián)合體節(jié)約內(nèi)存
Reason(原因)
A?union?allows a single piece of memory to be used for different types of objects at different times. Consequently, it can be used to save memory when we have several objects that are never used at the same time.
聯(lián)合體使用同一塊內(nèi)存管理在存在于不同時(shí)刻的不同類型的對(duì)象。也就是說,當(dāng)不同的對(duì)象永遠(yuǎn)不會(huì)同時(shí)使用的時(shí)候,使用聯(lián)合體可以節(jié)約內(nèi)存。
Example(示例)
union Value {
int x;
double d;
};
Value v = { 123 }; // now v holds an int
cout << v.x << '\n'; // write 123
v.d = 987.654; // now v holds a double
cout << v.d << '\n'; // write 987.654
But heed the warning: Avoid "naked" unions。
但是要留意這條準(zhǔn)則:C.181:避免原始的聯(lián)合體。
Example(示例)
// Short-string optimization
constexpr size_t buffer_size = 16; // Slightly larger than the size of a pointer
class Immutable_string {
public:
Immutable_string(const char* str) :
size(strlen(str))
{
if (size < buffer_size)
strcpy_s(string_buffer, buffer_size, str);
else {
string_ptr = new char[size + 1];
strcpy_s(string_ptr, size + 1, str);
}
}
~Immutable_string()
{
if (size >= buffer_size)
delete string_ptr;
}
const char* get_str() const
{
return (size < buffer_size) ? string_buffer : string_ptr;
}
private:
// If the string is short enough, we store the string itself
// instead of a pointer to the string.
union {
char* string_ptr;
char string_buffer[buffer_size];
};
const size_t size;
};
Enforcement(實(shí)施建議)
???
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c180-use-unions-to-save-memory
覺得本文有幫助?請(qǐng)分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
評(píng)論
圖片
表情
