She*_*evy 5 c++ memory-management stdstring
我正在开发一个程序,它将一个重要的数据结构存储为一个带有程序定义分隔符的非结构化字符串(所以我们需要遍历字符串并提取我们需要的信息)并且我们想将它转换为更结构化的数据类型.
本质上,这将需要一个结构,其中一个字段描述结构包含哪种数据,另一个字段是一个包含数据本身的字符串.在分配时始终知道字符串的长度.我们通过测试确定,每种数据类型所需的分配数量加倍是不可接受的成本.有没有办法在单个分配中为结构和结构中包含的std :: string分配内存?如果我们使用cstrings,我只需要在struct中有一个char*,并在为块和字符串分配足够大的块之后将其指向结构的末尾,但是如果可能的话我们更喜欢std :: string.
我的大部分经验都是使用C,所以请原谅这里显示的任何C++无知.
如果你有如此严格的内存需求,那么你将不得不放弃std::string。
最好的替代方法是找到或编写basic_string_ref(下一个 C++ 标准库的提案)的实现,它实际上只是一个 char* 加上一个大小。但它具有 的所有(非变异)功能std::basic_string。然后,您使用工厂函数来分配您需要的内存(您的结构大小+字符串数据),然后使用placement new 来初始化basic_string_ref.
当然,您还需要一个自定义删除函数,因为您不能仅将指针传递给“删除”。
考虑到之前链接到的实现basic_string_ref(及其关联的 typedef,string_ref),这里有一个工厂构造函数/析构函数,对于某些类型 T 来说需要有一个字符串:
template<typename T> T *Create(..., const char *theString, size_t lenstr)
{
char *memory = new char[sizeof(T) + lenstr + 1];
memcpy(memory + sizeof(T), theString, lenstr);
try
{
return new(memory) T(..., string_ref(theString, lenstr);
}
catch(...)
{
delete[] memory;
throw;
}
}
template<typename T> T *Create(..., const std::string & theString)
{
return Create(..., theString.c_str(), theString.length());
}
template<typename T> T *Create(..., const string_ref &theString)
{
return Create(..., theString.data(), theString.length());
}
template<typename T> void Destroy(T *pValue)
{
pValue->~T();
char *memory = reinterpret_cast<char*>(pValue);
delete[] memory;
}
Run Code Online (Sandbox Code Playgroud)
显然,您需要自己填写其他构造函数参数。并且您的类型的构造函数需要采用string_ref引用该字符串的 a 。
| 归档时间: |
|
| 查看次数: |
1166 次 |
| 最近记录: |