我想了解数组在 C++ 中的工作原理。一些关于 SO 的好线程,但我有一个问题我找不到答案是:
为什么可以声明没有大小的数组数据成员?我认为在 C++ 中数组大小必须是编译时常量?
例子:
#include<iostream>
class Object{
public:
Object(std::size_t n){
for(std::size_t i = 0; i<n; ++i) { array[i] ='X'; }
//prints 0 because 'sizeof' is compile-time operator
std::cout << "compile-time size: " << sizeof(array) << std::endl;
std::cout << "run-time size " << n << std::endl;
}
private:
char array[];
};
int main( int argc, char** argv )
{
Object obj(10); //10 chars
std::size_t n;
std::cin >> n;
Object obj2(n); //n chars in automatic storage i.e. on the stack??
}
Input:
n = 1000
Output:
compile-time size: 0
run-time size 10
compile-time size: 0
run-time size 1000
这是否意味着obj2的数组数据成员存储在自动存储中,但大小在运行时动态确定?
谢谢
最佳答案
Why is it possible to declare array data members with no size?
在标准 C++ 中,它不是。在 C 中,您可以将一个放在结构的末尾,以允许可变大小的数组 - 但您必须确保为您想要使用的任何大小分配足够的存储空间。一些 C++ 编译器可能允许将其作为非标准扩展。
Does this mean that obj2's array data member is stored in automatic storage, but the size is determined dynamically at runtime ?
不,这意味着数组没有任何存储空间,您正在覆盖堆栈的其他部分。这不是个好主意。
如果你想要一个动态数组,使用std::vector
。
关于c++ - 声明没有大小的数组数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26614439/