【发布时间】:2015-08-28 21:02:15
【问题描述】:
我提议更改一个库,其公共 API 当前如下所示:
typedef size_t enh; /* handle */
int en_open(enh *handle)
{
struct internal *e = malloc(...);
*handle = (enh)e;
return 0;
}
int en_start(enh handle)
{
struct internal *e = (struct internal*)handle;
return do_something(e);
}
这种用法,来回转换为size_t 会破坏严格的别名吗?
为了记录,我在公共 API 中提出了 struct internal 的典型不透明前向声明,如 this Programmers.SE question about the same code 所示。
【问题讨论】:
-
size_t是否保证足够宽以容纳指针?我不这么认为.. -
@EugeneSh。 Nope.
-
@Kninnug
void*不好,因为它使类型检查变得不可能。想想当您的界面中有两种不同的句柄类型时会发生什么。如果其中一个是void*,如果用户将它们混合在一起,编译器将不会捕获错误。使用适当的不透明指针,编译器将捕获这些错误。 -
@JensGustedt 是的。不透明指针优于
void*,优于uintptr_t,优于size_t。正是按照这个顺序:-) -
@rwong:短语其公共 API 目前看起来像确实表明显示的代码是“原始”样式。
标签: c api-design strict-aliasing