函数参数中的 struct 关键字以及 const 正确性
我的库中有一个不透明类型定义为:
typedef struct MyOpaqueType* MyType; // easier to type for client code
我无法使用 typedef 传递指向 const 结构的指针,因此某些函数看起来像:
void UsePointerToConst ( const struct MyOpaqueType * )
而不是:
void UserPointerToConst( const MyType ) // can't use, is really constant pointer
因此,考虑到这一点,我有两个问题: 参数列表中的 struct 关键字是否只在 C 中才需要? 有更好的方法吗?我应该创建一个 typedef 例如:
typedef const struct MyOpaqueType* ConstantMyType; ?
I have an opaque type in my library defined as:
typedef struct MyOpaqueType* MyType; // easier to type for client code
I can't pass a pointer-to-const struct around using the typedef, so some functions look like:
void UsePointerToConst ( const struct MyOpaqueType * )
instead of:
void UserPointerToConst( const MyType ) // can't use, is really constant pointer
So, given this, I have two questions:
Is the struct keyword in the parameter list only necessary in C?
Is there a better way to do this? Should I create a typedef such as:
typedef const struct MyOpaqueType* ConstantMyType; ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的。请参阅 Jens Gustedt 的回答。只是
typedef
结构体,而不是指针。这样做更好,因为typedef
,而不是每个 {MyOpaqueType
、MyOpaqueType *
、MyOpaqueType const *、
MyOpaqueType *const
和MyOpaqueType const *const
} 以及涉及restrict
的所有变体(不存在于C++),FILE *
)。也没有危险;当有人忘记
*
时,他们会收到编译器错误。Yes.See Jens Gustedt's answer.Just
typedef
the struct, not the pointer. This is better becausetypedef
instead of one for each of {MyOpaqueType
,MyOpaqueType *
,MyOpaqueType const *
,MyOpaqueType *const
andMyOpaqueType const *const
} and all variants involvingrestrict
(which doesn't exist in C++),FILE *
).There's also no danger; when someone forgets the
*
, they get a compiler error.在 C++ 中,只要没有其他标识符具有该名称,就假定
typedef
与struct
同名。因此,类似接收 struct stat* 作为参数的函数 stat 之类的东西:在 C++ 中甚至是允许的。 (这是一个真实世界的示例。)
因此,您最好使用前向声明,例如
在标识符和结构名称空间中保留标记
toto
。然后您可以为 C 和 C++ 声明函数接口。但如果您也想从 C 访问它,请不要忘记extern "C"
。另请参阅:这个答案和结构标签不是 C++ 中的标识符。
In C++ a
typedef
of the same name as astruct
is assumed as long as there is no other identifier with that name. So something like a functionstat
that receives astruct stat*
as an argument:is even allowed in C++. (This is a real world example.)
So you are always better of with forward declarations like
which reserves the token
toto
in the identifier and in the struct name space. Then you can have your function interface declared for C and C++. But don't forget theextern "C"
if you want to access it from C, too.See also: this answer on SO and struct tags are not identifiers in C++.
在 C++ 中根本不需要 typedef。只需使用前向声明:
然后根据需要传递
MyType const *
、MyType *
、MyType const &
等。You don't need the typedef at all in C++. Just use a forward declaration:
Then pass around
MyType const *
,MyType *
,MyType const &
etc as and when required.