Is it interesting to create a type just for a pointer to a type?

5

I've seen it doing a

MinhaEstrutura * 

be explicitly typed as

typedef MinhaEstrutura * pMinhaEstrutura;

Why not always do this and get rid of having to rename?

    
asked by anonymous 12.01.2017 / 11:16

1 answer

4

It's all about semantics. What is the intent of your code? Should he know there's a pointer there? Then leave the pointer exposed and do not create a type to leave the pointer opaque. Creating a type so indicates that you should not tinker with a pointer.

If the intent is not to show that you have a pointer there, why use the p prefix in the type that is the Hungarian notation for pointer? The biggest mistake is there. Unless the intention was to show that it is a pointer, then the typedef should not be used.

In fact this will not relieve "derreferencing", so it is not so opaque like this:

#include <stdio.h>

typedef struct { int x; } MinhaEstrutura;

typedef MinhaEstrutura * MeuTipo;

int main(void) {
    MinhaEstrutura dado = { 1 };
    MeuTipo var = &dado; //teve que usar o operador para pegar o endereço
    printf("%d", var->x); //teve que usar -> para acessar o membro
}

See running on ideone . Also I put it in Github for future reference .

It is possible for the compiler to handle the pointer transparently, but in C and C ++ this is not done, so it is rarely advantageous to try the opacity. If it conforms to the language where pointers are everywhere or change language.

In C ++ it is easier to leave opaque. What some people do is leave the pointer inside a type and its access is done through overloaded operators, but it is not a simple typedef that will solve.

    
12.01.2017 / 11:16