首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

sizeof()什么时候返回0解决办法

2012-04-19 
sizeof()什么时候返回0在看webkit,看到JavaScriptCore/wtf/OwnPtrCommon.h有这么一段C/C++ codetemplate

sizeof()什么时候返回0
在看webkit,看到JavaScriptCore/wtf/OwnPtrCommon.h有这么一段

C/C++ code
    template <typename T> inline void deleteOwnedPtr(T* ptr)    {        typedef char known[sizeof(T) ? 1 : -1];        if (sizeof(known))            delete ptr;    }


很奇怪,sizeof()还会返回0?什么时候会发生?

[解决办法]
简单地说,没有,但是编译器都有扩展。其中有两个扩展。

int buf[0];
sizeof(buf); //0

另一个是
当sizeof 非法时,也就是说产生了编译错误,如同lz给出的代码。
试试这样
void * p = 0;
deleteOwnedPtr(p); //编译错误 void 不能用于sizeof
[解决办法]
http://stackoverflow.com/questions/2632021/can-sizeof-return-0-zero

Is it possible for the sizeof operator to ever return 0 (zero) in C or C++? If it is possible, is it correct from a standards point of view?

Answer:
In C++ an empty class or struct has a sizeof at least 1 by definition. From the C++ standard, 9/3 "Classes": "Complete objects and member subobjects of class type shall have nonzero size."

In C an empty struct is not permitted, except by extension (or a flaw in the compiler).

This is a consequence of the grammar (which requires that there be something inside the braces) along with this sentence from 6.7.2.1/7 "Structure and union specifiers": "If the struct-declaration-list contains no named members, the behavior is undefined".

If a zero-sized structure is permitted, then it's a language extension (or a flaw in the compiler). For example, in GCC the extension is documented in "Structures with No Members", which says:


GCC permits a C structure to have no members:
 struct empty { 
 }; 

 The structure will have size zero. In C++, empty structures are part of the language. G++ treats empty structures as if they had a single member of type char. 

热点排行