简体   繁体   中英

C++ anonymous structs?

A previous post of mine raised the topic of anonymous structs, with several commentators saying these were not allowed in C++.

Here is a construction that I use a lot: is this legal C++?

const int HeaderSize = 8192;
struct Header
{
    union
    {
        struct
        {
            int r;
            // other members
        };
        unsigned char unused[HeaderSize]; // makes Header struct's size remain constant as members are added to the inner struct
    };
    // Default constructor
    Header()
    {

    }
};

In Standard C++ there cannot be an anonymous struct ( see here for why ), although mainstream compilers offer it as an extension.

I guess you intend to read binary data directly into this struct. That is frowned on in Modern C++, and it is preferred to use data serialization.

If you persist with reading directly to the struct perhaps an alternative would be:

struct Header
{
    int r;
    // other members;
};

struct Image
{
    Header hdr;
    char padding[HeaderSize - sizeof(Header)];
    // rest of image
};

Anonymous structs are not a thing in C++, only anonymous unions. So you have to provide a name for the struct.

Furthermore, anonymous unions cannot have nested types either, which means you have to take the struct out of the union too.

So, combining those two bits, this means you need to write:

const int HeaderSize = 8192;
struct Header
{
    struct Members
    {
        int r;
        // other members
    };

    union
    {
        Members members;
        unsigned char unused[HeaderSize]; // makes Header struct's size remain constant as members are added to the inner struct
    };

    // Default constructor
    Header()
    {

    }
};

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