被typedef'ing认为是不好的做法,指针类型? [英] Is typedef'ing a pointer type considered bad practice?

查看:166
本文介绍了被typedef'ing认为是不好的做法,指针类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  指针的typedef一个好主意吗?

我见过许多API这个怪胎我用:

I've seen this oddity in many APIs I have used:

typedef type_t *TYPE;

我的意思是声明类型的变量键入不说清楚,其实是一个指针声明。

My point is that declaring a variable of type TYPE will not make it clear that in fact a pointer is declared.

你和我一样,认为这带来了很多困惑?那是不是意味着执行封装,或有其他原因呢?你认为这是一个不好的做法呢?

Do you, like me, think that this brings a lot of confusion? Is this meant to enforce encapsulation, or there are other reasons as well? Do you consider this to be a bad practice?

推荐答案

在一般情况下,这是一个不好的做法。该显著的问题是,它不与常量发挥好

In general, it's a bad practice. The significant problem is that it does not play well with const:

typedef type_t *TYPE;
extern void set_type(TYPE t);

void foo(const TYPE mytype) {
  set_type(mytype);  // Error expected, but in fact compiles
}

为了为的作者富()来恩preSS他们真正的意思,它提供了库 TYPE 还必须提供 CONST_TYPE

In order for the author of foo() to express what they really mean, the library that provides TYPE must also provide CONST_TYPE:

typedef const type_t *CONST_TYPE;

富()可以有签名无效美孚(CONST_TYPE MYTYPE),在这一点上,我们已经陷入了一场闹剧。

so that foo() can have the signature void foo(CONST_TYPE mytype), and at this point we have descended into farce.

因此​​,一个经验法则:

Hence a rule of thumb:

请结构的类型定义(尤其是不完整的结构),而不是指向的结构。

Make typedefs of structs (particularly incomplete structs), not pointers to those structs.

如果底层结构的定义是不被公开发布(这往往是值得称赞的),那么封装应由结构不完整,而不是由不方便的typedef提供的:

If the definition of the underlying struct is not to be publicly available (which is often laudable), then that encapsulation should be supplied by the struct being incomplete, rather than by inconvenient typedefs:

struct type_t;
typedef struct type_t type_t;

void set_type(type_t *);
int get_type_field(const type_t *);

这篇关于被typedef'ing认为是不好的做法,指针类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆