防御性类型检测

来源:互联网 发布:万磁王和x教授 知乎 编辑:程序博客网 时间:2024/05/20 09:22

今天在看源码的时候 浏览到一个地方

先上代码

</pre><pre name="code" class="cpp"># define CHECKED_SK_CMP_FUNC(type, p) \    ((int (*)(const void *, const void *)) \        ((1 ? p : (int (*)(const type * const *, const type * const *))0)))
大家可能一头雾水,为何1为true,还要后边的那一堆呢,

目的就是今天的主题,防御性类型检查,确保你传入的p类型是

(int (*)(const type * const *, const type * const *))这种类型.所以传参要谨慎
再举个例子
int* p = NULL;
1?p:(double*)p //error
1?p:(int*)p    //ok
各位你们明白了吗,如果p不是()里面的类型,那么就会报一个编译错误说无法转换

0 0
原创粉丝点击