简体   繁体   中英

copy constructor for struct containing a union

Consider the code

struct S
{
    S(){...}
    union
    {
        int* pi;
        double* pd;
    }
    // additional member functions etc
};

Suppose we also have setters for pi and pd , that is, memory is being allocated depending on which member of the union is being selected.

How would you write a copy constructor for S ? How can you know which member of the union is "active"? One way is to have an additional flag that you set when you "activate" one of the members, is there any other way?

How can you know which member of the union is "active"?

You can't, unless you store a flag to tell you which way it has been assigned. It is common to store such "selector" flag in the enclosing class, for example:

struct S
{
    S(){...}
    union
    {
        int* pi;
        double* pd;
    }
    enum {
        UseIntPtr,
        UseDoublePtr
    } unionSelector;
    // additional member functions etc
};

You would set unionSelector to UseIntPtr when you set pi , or to UseDoublePtr when you set pd . Then you would have a flag to use in your copy constructor, assignment operator, and so on.

If the union is a POD (Plain Old Data) then you can use memcpy . Works great.

In your case you'd have to give the union a name so you can do sizeof myunion .

memcpy(&this->myunion, &other.myunion, sizeof myunion)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM