<分区>
Possible Duplicate:
Typedef pointers a good idea?
我在我使用的许多 API 中都看到过这种奇怪的现象:
typedef type_t *TYPE;
我的观点是,声明类型为 TYPE
的变量并不能表明实际上声明了一个指针。
你和我一样认为这会带来很多困惑吗?这是为了强制封装,还是还有其他原因?您认为这是一种不好的做法吗?
<分区>
Possible Duplicate:
Typedef pointers a good idea?
我在我使用的许多 API 中都看到过这种奇怪的现象:
typedef type_t *TYPE;
我的观点是,声明类型为 TYPE
的变量并不能表明实际上声明了一个指针。
你和我一样认为这会带来很多困惑吗?这是为了强制封装,还是还有其他原因?您认为这是一种不好的做法吗?
最佳答案
一般来说,这是一种不好的做法。重要的问题是它不能很好地与 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
:
typedef const type_t *CONST_TYPE;
以便 foo()
可以具有签名 void foo(CONST_TYPE mytype)
,此时我们陷入了闹剧。
因此有一条经验法则:
Make typedefs of structs (particularly incomplete structs), not pointers to those structs.
如果底层结构的定义不是公开可用的(这通常是值得称赞的),那么封装应该由不完整的结构提供,而不是由不方便的类型定义提供:
struct type_t;
typedef struct type_t type_t;
void set_type(type_t *);
int get_type_field(const type_t *);
关于c - typedef'ing 指针类型被认为是不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3781932/