【发布时间】:2010-07-26 08:31:54
【问题描述】:
我需要在一块可靠的内存中分配一个此结构的数组。 “char *extension”和“char *type”的长度在编译时是未知的。
struct MIMETYPE
{
char *extension;
char *type;
};
如果我使用“new”操作符来单独初始化每个元素,内存可能会分散。这就是我尝试为其分配单个连续内存块的方式:
//numTypes = total elements of array
//maxExtension and maxType are the needed lengths for the (char*) in the struct
//std::string ext, type;
unsigned int size = (maxExtension+1 + maxType+1) * numTypes;
mimeTypes = (MIMETYPE*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
但是,当我尝试像这样加载数据时,当我稍后尝试访问它时,数据全部乱序和分散。
for(unsigned int i = 0; i < numTypes; i++)
{
//get data from file
getline(fin, line);
stringstream parser.str(line);
parser >> ext >> type;
//point the pointers at a spot in the memory that I allocated
mimeTypes[i].extension = (char*)(&mimeTypes[i]);
mimeTypes[i].type = (char*)((&mimeTypes[i]) + maxExtension);
//copy the data into the elements
strcpy(mimeTypes[i].extension, ext.c_str());
strcpy(mimeTypes[i].type, type.c_str());
}
谁能帮帮我?
编辑:
unsigned int size = (maxExtension+1 + maxType+1);
mimeTypes = (MIMETYPE*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size * numTypes);
for(unsigned int i = 0; i < numTypes; i++)
strcpy((char*)(mimeTypes + (i*size)), ext.c_str());
strcpy((char*)(mimeTypes + (i*size) + (maxExtension+1)), type.c_str());
【问题讨论】:
-
有什么理由不能只使用
std::vector和std::string? -
@cppnick:它是
new[]的安全包装器。我想我不明白的是:为什么它 all 必须是连续的? 可能 不是进行过早的代码混乱优化的好理由。首先让它工作,使用好的、现代的、干净的 C++,然后 profile 它,看看什么是慢的(不是什么可能是慢的),然后优化它。 -
最好的方法是在没有连续内存要求的情况下编写它。然后放置一整套单元测试来验证行为。然后,如果您确实需要性能改进,请重构您选择的分配模型,使用测试作为安全网来捕获(更复杂的)代码中的任何错误。
-
为什么你认为连续分配会提高性能?除非您正在进行线性搜索(如果性能很重要,您不应该这样做),那么您将以随机顺序访问字符串,并且位置可能不会有任何区别。
-
决定只使用 std::string。
标签: c++