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

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

问题描述

可能的重复:
Typedef 指针是个好主意吗?

我在我使用过的许多 API 中都看到过这种奇怪的现象:

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

typedef type_t *TYPE;

我的观点是声明一个 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?

推荐答案

总的来说,这是一个不好的做法.重要的问题是它不能很好地与 const 配合使用:

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
}

为了让foo()的作者表达他们真正的意思,提供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;

这样foo()就可以有void foo(CONST_TYPE mytype)的签名,此时我们就陷入了闹剧.

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

因此有一个经验法则:

制作结构体(尤其是不完整结构体)的类型定义,而不是指向这些结构体的指针.

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

如果底层结构的定义不是公开可用的(这通常是值得称赞的),那么封装应该由不完整的结构提供,而不是由不方便的类型定义提供:

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天全站免登陆