Does typedef have any effect for itself?

I came across some C ++ code that has the following:

typedef Request Request; 

Is it just a no-op or the actual typedef effect has an effect, and if so, what effect does it have?

+6
source share
2 answers

Typedef is permitted if the name already refers to a certain type.

It is legal:

 typedef int Request; typedef Request Request; // Redefines "Request" with no effect 

Is not:

 typedef Request Request; // Illegal, first "Request" doesn't name a type. 

There is a concrete example in the standard related to this. C ++ 2003, Β§7.1.3 / 2:

In a given non-class domain, the typedef specifier can be used to override the name of any type declared to this extent refers to the type to which it already refers. [Example:

 typedef struct s { /* ... */ } s; typedef int I; typedef int I; typedef II; 

-end example]

+9
source

If Request is passed only as a parameter, it looks like an opaque pointer .
Must be

 typedef struct Request Request 

somewhere in the code. (see comments to your question)
This is used to define the API and hide implementation details. That way, you can change the implementation later without changing the API again.

The client does not need to know anything about the acutal type - its just a pen.
Everything you want to do with this should be done using api methods (create, delete, load, init, ...)
Typically, the Request descriptor will be passed to something more meaningful in the api implementation. This was / is usually performed in old C.

0
source

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


All Articles