static arrays defined with unspecified size, empty brackets?(使用未指定大小、空括号定义的静态数组?)
问题描述
对于下面的 C++ 代码片段:
For the C++ code fragment below:
class Foo {
int a[]; // no error
};
int a[]; // error: storage size of 'a' isn't known
void bar() {
int a[]; // error: storage size of 'a' isn't known
}
为什么成员变量也不会导致错误?这个成员变量是什么意思?
why isn't the member variable causing an error too? and what is the meaning of this member variable?
我通过 CodeBlocks 8.02 使用 gcc 版本 3.4.5(mingw-vista special).
I'm using gcc version 3.4.5 (mingw-vista special) through CodeBlocks 8.02.
在 Visual Studio Express 2008 - Microsoft(R) C/C++ Optimizing Compiler 15.00.30729.01 for 80x86 上,我收到以下消息:
On Visual Studio Express 2008 - Microsoft(R) C/C++ Optimizing Compiler 15.00.30729.01 for 80x86, I got the following messages:
class Foo {
int a[]; // warning C4200: nonstandard extension used : zero-sized array in struct/union - Cannot generate copy-ctor or copy-assignment operator when UDT contains a zero-sized array
};
int a[];
void bar() {
int a[]; // error C2133: 'a' : unknown size
}
现在,这也需要一些解释.
Now, this needs some explaination too.
推荐答案
C99 支持称为灵活"数组成员的东西,它允许成为结构的最后一个成员.当您动态分配这样的结构时,您可以增加从 malloc() 请求的数量,以便为数组提供内存.
C99 supports something called a 'flexible' array member that is allowed to be the last member of a struct. When you dynamically allocate such a struct you can increase the amount requested from malloc() to provide for memory for the array.
一些编译器将此作为 C90 和/或 C++ 的扩展添加.
Some compilers add this as an extension to C90 and/or C++.
所以你可以有如下代码:
So you can have code like the following:
struct foo_t {
int x;
char buf[];
};
void use_foo(size_t bufSize)
{
struct foo_t* p = malloc( sizeof( struct foo_t) + bufSize);
int i;
for (i = 0; i < bufSize; ++i) {
p->buf[i] = i;
}
}
您不能直接定义具有灵活数组成员的结构(作为本地或全局/静态变量),因为编译器不知道要为其分配多少内存.
You can't define a struct with a flexible array member directly (as a local or a global/static variable) as the compiler won't know how much memory to allocate for it.
老实说,我不确定您如何使用 C++ 的 new 运算符轻松使用这样的东西 - 我认为您必须使用 malloc() 为对象分配内存 并使用放置 new.也许可以使用一些特定于类/结构的 operator new 重载...
I'm honestly not sure how you'd easily use such a thing with C++'s new operator - I think you'd have to allocate the memory for the object using malloc() and use placement new. Maybe some class/struct specific overload of operator new could be used...
这篇关于使用未指定大小、空括号定义的静态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用未指定大小、空括号定义的静态数组?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
