Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

C11 supports anonymous structures, like so:

struct Foo
{
    struct
    {
        size_t x, y;
    };
};
struct Foo f;
f.x = 17;
f.y = 42;

Basically, the members of such a struct are treated as if they were members of the enclosing struct or union (recursively, if the enclosing structure was itself anonymous).

What was the rationale for C++11 not also including anonymous structures? They're only uncommonly useful (mostly inside unions, to eliminate the typing of an identifier for the struct), certainly. But they seem an obvious enough addition to the specification (and one already implemented by many compilers) that surely they must have been discussed, at the very least to preserve compatibility with the C11 standard. So why weren't they added?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
325 views
Welcome To Ask or Share your Answers For Others

1 Answer

Little effort has been made to maintain compatibility between C++ and C as the two languages evolve. Notice that variable length stack arrays have been in C since 1999, but weren't included in C++11. While they generally don't introduce things that contradict one another, the C++ committee isn't exactly bending over backwards to make sure that C++11 is compatible with versions of C beyond C89.

Furthermore, this feature would be quite complex in C++, because a struct is nothing more than a class. And an anonymous struct/class should have all of the features of a regular struct/class, yes? Otherwise, what's the point of having it?

What would it mean to construct a nameless struct? How would you define the constructor? Something as simple as:

struct Foo
{
    struct
    {
        size_t &x;
    };
};

is simply not possible because the inner struct has no constructor. And there's no way to specify one. A struct cannot construct the members of another struct within it.

For something like this:

struct Foo
{
    size_t outer;
    struct
    {
        void SomeFunc();
        size_t x;
    };
};

What this pointer does SomeFunc get? What would the type of this be, the nameless and unnamed type? How would you even define SomeFunc outside of the struct? The name of SomeFunc can't be Foo::SomeFunc, because SomeFunc lives in an inner scope.

It's just too complex for C++ to deal with. And certainly not worthwhile enough to bother with adding that complexity for.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...