开发者

Assignment to unions of members

Let's say I have a class with union members in it:

class ClassX {
public:
  union {
    StructA * A;
    StructB * B;
    };
  }
开发者_JAVA百科

If I have pointers x1 and x2 to different ClassX objects, does this:

x1->A = x2->A;

Have the same effect as this:

x1->B = x2->B;

? Thanks.


For most practical purposes, on most implementations, those two statements would have the same effect, however it's not guaranteed. If the member that you read from a union isn't the last member that was writted to the union the behaviour of the program is undefined.

Because both members of the union are pointers to structs it is very likely that they occupy the same size and have analogous representations so assigning either union member is likely to correctly assign the other union member if that's what was actually stored in the source union.


What kind of answer do you expect?

A formal and pedantic one? If so, then there's simply no answer to that question. C++ language does give you any formal opportunity to compare the effects of these two assignments. If you assigned ClassX::A, you can only read ClassX::A and not ClassX::B. If you assigned ClassX::B, you can only read ClassX::B and not ClassX::A. In other words, there's no meaningful reason to even care whether the effects are the same or not. The language simply does not allow you to care about it. If your code somehow relies on it, then its behavior is undefined, as far as formal C++ is concerned.

As for the real-life practical answer to that question... yes, the effects should be the same in any reasonable implementation of the language.


C++1x Standard Draft, Section 9.5.1

In a union, at most one of the data members can be active at any time, that is, the value of at most one of the data members can be stored in a union at any time. [Note: one special guarantee is made in order to simplify the use of unions: If a POD-union contains several POD-structs that share a common initial sequence (class.mem), and if an object of this POD-union type contains one of the POD-structs, it is permitted to inspect the common initial sequence of any of POD-struct members; see class.mem. ]

Do note the special guarantee.


These do not have the same effect unless StructA and StructB have the same size. The first line you posted copies all of the memory occupied by x2->A into x1->A, while the second does the same thing for B. A and B occupy an overlapping area of memory, but they may be different sizes, in which case the two statements are not equivalent.


The operations should be identical. But that might not be the case if you've overloaded the assignment operator for either of those two pointer types.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜