Rod*_*zar 5 c++ struct pointers typedef incomplete-type
以下代码编译良好。
标头.h:
typedef struct Placeholder_Type* Placeholder;
Run Code Online (Sandbox Code Playgroud)
实现.cpp:
#include "header.h"
void doSomething(Placeholder t) {
(void) t;
}
int main() {
int *a = new int();
doSomething((Placeholder)a);
}
Run Code Online (Sandbox Code Playgroud)
编译命令:
clang++ impl.cpp
Run Code Online (Sandbox Code Playgroud)
Placeholder_Type 类型在任何地方都不存在,并且在输出二进制文件中也不作为符号存在。
为什么为不存在的类型创建 typedef 是合法的?
为什么我可以使用不存在的类型创建函数?
这是否相当于仅使用 void* 但命名为“Placeholder”?
struct Placeholder_Type
声明结构Placeholder_Type
(但不定义它),无论它出现在哪里。即使它在typedef
. 因此,您不会为不存在的结构创建 typedef,而是为刚刚声明的结构创建 typedef(如果编译器尚不知道,则创建该结构)。
至于为什么,因为这样可以使结构体的定义远离公共接口。例如,这是在 C 中实现不透明对象的典型方法:
// mytype.h
typedef struct MytypeImpl* Mytype;
Mytype create_mytype();
void destroy_mytype(Mytype o);
void do_something_with_mytype(Mytype o, int i);
// mytype.c
struct MytypeImpl {
int something;
int otherthing;
};
Mytype create_mytype() {
Mytype o = malloc(sizeof(*o));
o->something = 0;
o->otherthing = 0;
return o;
}
void destroy_mytype(Mytype o) {
free(o);
}
// etc.
Run Code Online (Sandbox Code Playgroud)
当然,个人风格可能在细节上有所不同。但关键是结构体的定义在 mytype.c 之外不可见,因此没有人可以访问数据成员。
归档时间: |
|
查看次数: |
549 次 |
最近记录: |