本文介绍了宏定义ARRAY_SIZE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了谷歌的V8项目globals.h时遇到下面的宏定义。

  //这位前pression ARRAY_SIZE(a)是类型的编译时间常数
//为size_t从而重新presents给定的元素数
//数组。您应该只使用ARRAY_SIZE的静态分配
//数组。#定义ARRAY_SIZE(一)\\
  ((sizeof的(A)/的sizeof(*(一)))/ \\
  的static_cast&所述;为size_t>(!(sizeof的(一)%的sizeof(*(一)))))

我的问题是后半部分:的static_cast<为size_t>)((的sizeof(A)%的sizeof(*(一)))!)。在我心中有一件事是:由于后期将始终计算为 1 ,这类型的为size_t ,因此整个前pression将晋升为为size_t 。如果这个假设是正确的,那么总会有另一个问题:因为的sizeof的的返回类型运算符是为size_t,为什么这样的推广是必要的吗?什么是这样定义宏的好处?

非常感谢您的阅读。


解决方案

Ideally the later part will evaluate to bool (i.e. true/false) and using static_cast<>, it's converted to size_t.

I don't know if this is ideal way to define a macro. However, one inspiration I find is in the comments: //You should only use ARRAY_SIZE on statically allocated arrays.

Suppose, if someone passes a pointer then it would fail for the struct (if it's greater than pointer size) data types.

struct S { int i,j,k,l };
S *p = new S[10];
ARRAY_SIZE(p); // compile time failure !

[Note: This technique may not show any error for int*, char* as said.]

这篇关于宏定义ARRAY_SIZE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 09:55