简体   繁体   English

一长串大型结构:更喜欢堆或堆栈分配?

[英]Long array of big structs: prefer heap or stack allocation?

I have a struct with much data in it: 我有一个结构,里面有很多数据:

struct myStruct
{
  char name[128], desc[128];
  struct Prm { char p_name[32]; int p_val; } parameter[512];
  char Reserved[256]; 
};

The size of the whole struct, as shown in the above example, is 18944 bytes assuming there's no padding; 如上例所示,假设没有填充,整个结构的大小为18944字节。 I need 128 of these, that sums up in 2424832 bytes, it's more than 2 Megabytes. 我需要其中的128个,总和为2424832字节,超过2 MB。

I need to declare this array in the global scope, what's the best way to allocate it? 我需要在全局范围内声明此数组,分配它的最佳方法是什么? Shall I just do myStruct myData[128]; 我应该做myStruct myData[128]; or declare it as a pointer and initialize with new[] then delete[] it when the program quits? 还是将其声明为指针并使用new[]进行初始化,然后在程序退出时将delete[] Or maybe a vector? 还是矢量?

Will declaring it as a simple array mess with the stack? 将其声明为一个简单的数组会与堆栈混淆吗? How can I be sure that it isn't problematic? 我如何确定它没有问题?

列表中更好的选择是std::vector<>

The risk with large arrays is busting your stack. 大型阵列的风险是破坏堆栈。 Global variables are not in the stack, so it's fine. 全局变量不在堆栈中,所以很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM