C++ Union, Struct, Member type

﹥>﹥吖頭↗ 提交于 2019-12-12 08:12:58

问题


If I have a class:

class Odp
{
    int i;
    int b;
    union
    {
         long f;
         struct
         {
               WCHAR* pwszFoo;
               HRESULT hr;
         };
    };

}

Union means that, of all values listed, it can only take on one of those values at a time? How does that work in terms of accessing these variables? How would I access hr directly? If I set hr, what happens if I try to access f?


回答1:


This is a very fraught area in the C++ standard - basically a union instance, per the standard can only be treated at any one time as if it contained one "active" member - the last one written to it. So:

union U {
   int a;
   char c;
};

then:

U u;
u.a = 1;
int n = u.a;
u.c = 2;
char c = u.c;

is OK, but:

U u;
u.a = 1;
char c = u.c;

is not. However, there are vast volumes of existing code that say that both are OK. and in neither, or any, case will an exception be thrown for an "invalid" access. The C++ language uses exceptions exceptionally (!) sparingly.

Basically, if you find yourself using unions in your C++ code to deal with anything but C libraries, something is wrong.




回答2:


Every time you set (write to) a member of a union, you essentially make it "active". You are only allowed to read the currently active member of the union. It means that it is your responsibility to remember somehow which member is active at each moment in time.

Attempting to access the inactive member of a union leads to undefined behavior.

Keep in mind also that your code is not valid C++. There's no such thing as "anonymous struct" in C++. Your struct member has to have a name. If your compiler accepts it, it is just a non-standard extension supported by your specific compiler.




回答3:


Right, with a union the same memory locations will be used to represent a single one of the members at any given time. So if you have an instance of the union and set the value of hr, you will get garbage if you then try to read the value of f.

Try using the following to access hr:

union a;
a.hr = NULL;



回答4:


It just means you can access the same memory as either the long, or the struct.

To access hr:

Odp o1;
o1.hr;

Interesting link: http://www.cplusplus.com/forum/general/18816/




回答5:


Attempt to access "f" will give you some result. It will likely be representation other member of union as data type of "f", i.e. in this case you are likely will be reading partial or entire content of the "pwszFoo" represented as "long" data type. General concept is easy - union members share the same location in memory.



来源:https://stackoverflow.com/questions/3071806/c-union-struct-member-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!