Using typedef when declaring structures in C ++

I personally don't like the old C-style structure declarations:

typedef struct {} NewType;

ctags does the ugly anonymous types of this and makes debugging difficult. Is there any reason in C ++ code using a typedef struct instead of a simple structure, except that the code is used in both C and C ++?

Regards, Valentin

+3
source share
3 answers

One of the main disadvantages of these

typedef struct tagSomethingSomething SomethingSomething;

lies in the fact that forward-declarations are not possible with the commonly used name typedef'fed.

Yes, this is C-ism (kudos sbi), and there are C ++ codebases where it is - unfortunately (still) common.

+3
source

C-ism. C ,

struct NewType {};
enum SomeEnum {};

struct NewType enum SomeEnum .

++ . , , C, .

+3

@sbi: , : , .. ++ , , "struct hack", typedef, typedef . , , , . "C" .

, , :

struct X { struct {int a; } b; } x;
x.b.a; // OK

struct X has an external connection, although type b is anonymous. Anonymous structures can be used on the stack or in static storage, but unlike anonymous unions, which will not have advantages over individual variables. I'm not even sure that C ++ allows anonymous structures.

-1
source

Source: https://habr.com/ru/post/1779825/


All Articles