在C ++中使用联合是一个好的做法吗? [英] Is it a good practice to use unions in C++?

查看:131
本文介绍了在C ++中使用联合是一个好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要这样定义一个类:

  class Color 
{
private:
union Data
{
unsigned int intValue;
unsigned char argbBytes [4];
}

private:
数据m_data;
};

另一种方法当然是将数据定义为整数, p>

我想知道哪一种是首选方法。这里的矛盾是,我有远程记忆某人的提醒不要使用联合,但在这种情况下似乎是一个更清洁的解决方案。

解决方案

工会可以很好,只要仔细使用它们即可。



它们可以通过两种方式使用:


  1. 允许以多种方式访问​​单一类型的数据(如在示例中,访问颜色为int或


  2. 创建一个多态类型(一个值可以包含一个int或一个浮点数)。


案例(1)很好,因为你不改变类型的含义 - 你可以读写任何成员的联盟没有打破任何东西。



案例(2)非常有用,但是非常危险,因为你需要总是从联合中访问正确类型的数据。如果你写一个int并尝试读它作为一个float,你会得到一个无意义的价值。除非内存使用是你的首要考虑,也许最好使用一个简单的结构体,其中包含两个成员。



联合体在C中至关重要。在C ++中,更好的方式来实现相同的目的(例如,一个类可以用于包装一个值,并允许它以不同的方式访问)。但是,如果您需要原始性能或存在严重的内存情况,工会仍然可能是一种有用的方法。


I need to define a class like this:

class Color
{
private:
   union Data
   {
       unsigned int intValue;
       unsigned char argbBytes[4];
   }

private:
    Data m_data;
};

Another way is of course define the data as integer and cast it to char array whenever necessary.

I'm wondering which one is the preferred way. The contradiction here is that I have remote memory of someone's remind not to use union anymore however it seems to be a cleaner solution in this case.

解决方案

Unions can be fine, as long as you use them carefully.

They can be used in two ways:

  1. To allow a single type of data to be accessed in several ways (as in your example, accessing a colour as an int or (as you probably intended) four chars)

  2. To make a polymorphic type (a single value that could hold an int or a float for example).

Case (1) Is fine because you're not changing the meaning of the type - you can read and write any of the members of the union without breaking anything. This makes it a very convenient and efficient way of accessing the same data in slightly different forms.

Case (2) can be useful, but is extremely dangerous because you need to always access the right type of data from within the union. If you write an int and try to read it back as a float, you'll get a meaningless value. Unless memory usage is your primary consideration it might be better to use a simple struct with two members in it.

Unions used to be vital in C. In C++ there are usually much nicer ways to achieve the same ends (e.g. a class can be used to wrap a value and allow it to be accessed in different ways). However, if you need raw performance or have a critical memory situation, unions may still be a useful approach.

这篇关于在C ++中使用联合是一个好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆