C++中如何使用联合体节约内存

发布时间:2021-07-30 16:14:33 作者:Leah
来源:亿速云 阅读:167

这期内容当中小编将会给大家带来有关C++中如何使用联合体节约内存,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

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(示例)

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。

但是要留意这条准则:C.181:避免原始的联合体。

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

上述就是小编为大家分享的C++中如何使用联合体节约内存了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. C++小知识:不要节约代码行数
  2. C++中如何检查内存泄露

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:Linux中如何使用NTFS区分磁盘

下一篇:C++中怎么使用RAII防止资源泄露

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》