using typedef in declaring structs in C++
I personally don't like old C-style of struct declarations like that:
typedef struct {} NewType;
ctags makes ugly anon typ开发者_运维百科es of this and make the debugging difficult. Is there any reason in C++ code using typedef struct instead of simply struct, except the code is used in both C and C++?
Regards, Valentin
One major drawback of those
typedef struct tagSomethingSomething SomethingSomething;
is that, forward-declarations are not possible with the commonly used typedef'fed name.
Yes, it's a C-ism (kudos sbi) and there are c++-codebases, where it - unfortunately - (still) is common.
That's a C-ism. In C, structs and enums effectively have their one namespaces, so for
struct NewType {};
enum SomeEnum {};
you'd have to write struct NewType
and enum SomeEnum
to refer to.
In C++ this isn't necessary. So, Unless you write a header which needs to be parsed by a C compiler, too, you shouldn't use this.
@sbi: I think no: could be wrong, but .. in C++ it isn't an anonymous struct, there's a special rule called the "struct hack" which makes an ordinary struct tagged with the typedef name, so the typedef name becomes the class name as well. This is required because functions with external linkage require arguments of class type to have external linkage too, and that implies having an external name. Without this hack, only extern "C" functions could manipulate the struct.
The only place you could use an anonymous struct would be inside another structure:
struct X { struct {int a; } b; } x;
x.b.a; // OK
struct X has external linkage even though the type of b is anonymous. Anonymous structs could be used on the stack or in static storage but unlike anonymous unions, that would provide no advantage over separate variables. I'm not even sure C++ allows anonymous structs.
精彩评论