问题描述
我正在尝试声明一个占用零字节的C ++变量。它是联合的,我从int [0]类型开始。我不知道这是否实际上是零字节(尽管sizeof(int [0])为0)。我需要一种更好的方法来声明一个0字节的类型,并希望可以将其类型定义为nullType或emptyType。该变量是一个并集,因此在最终存储器中仍然保留。我试着在无效的机会上尝试作废,但C ++抱怨。我使用的是Ubuntu 10.10,具有当前版本的内核和最新的GCC。
这是工会:
union RandomArgumentTypesFirst
{
uint uintVal;
nullType nullVal;
}
这是typedef:
typedef int [0] nullType;
编译器对typedef这么说:
错误:变量或字段'nullVal'声明为voidmake [2]:
当我键入 int [0]
时,它可以工作。有建议吗?
编辑:
正如@fefe在评论中所说, int [0]
可以由编译器作为扩展提供。 GCC的网站上说默认情况下编译器具有许多扩展。
typedef拼写错误:
typedef int nullType [0];正如其他人指出的那样,您不能拥有大小为0的对象;但是,编译器可以(并且经常这样做)提供 Empty基类
优化。
-
- (空成员优化)
I'm trying to declare a C++ variable that takes up zero bytes. Its in a union, and I started with the type as int[0]. I don't know if that is actually zero bytes (although sizeof(int[0]) was 0). I need a better way to declare a 0 byte type, and hopefully one that can be typedefed to something like nullType or emptyType. The variable is in a union, so in the end memory is reserved anyway. I tried void on the off chance it would work, but C++ complained. I'm using Ubuntu 10.10, with a current version of the kernel, and an up-to-date GCC.
Here's the union:
union RandomArgumentTypesFirst
{
uint uintVal;
nullType nullVal;
}
And here is the typedef:
typedef int[0] nullType;
The compiler says this about the typedef:
error: variable or field ‘nullVal’ declared voidmake[2]:
When I typed in int[0]
, it worked. Any suggestions?
EDIT:As @fefe said in the comments, the int[0]
may be provided as an extension by the compiler. GCC's website says that the compiler has many extensions by default.
解决方案 The typedef is misspelled:
typedef int nullType[0];
As others have pointed out, you cannot have an object of size 0; However, compilers can (and frequently do) provide the Empty Base Class
optimization.
- http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Empty_Base_Optimization
- http://www.cantrip.org/emptyopt.html ("empty member" optimization)
这篇关于是否可以有一个C ++类型占用0个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!