C++核心準則C.180:使用聯合體節約內存

C++核心準則C.180:使用聯合體節約內存

C.180: Use unions to save memory

C.180:使用聯合體節約內存

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.

聯合體使用同一塊內存管理在存在於不同時刻的不同類型的對象。因此,當不同的對象永遠不會同時使用的時候,使用聯合體可以節約內存。

Example(示例)

<code>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/<code>

But heed the warning: Avoid "naked" unions。

但是要留意這條準則:避免原始的聯合體。

Example(示例)

<code>// 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;
};/<code>

Enforcement(實施建議)

???

原文鏈接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c180-use-unions-to-save-memory


覺得本文有幫助?請分享給更多人。

面向對象開發,面向對象思考!


分享到:


相關文章: