在struct[]中分配char*指针值(结构成员)的最优化方法
most optimized approach to assign a char* pointer value (who is a struct member) in struct[]
我试图使结构的一些成员是一种类型的字符串的集合,因为字符串是'昂贵的'来处理我试图通过使用指针来最大化性能。
我尽我最大的努力从教程中学习,但是c++中有太多不同类型的字符串。
如果值的类型是char*
,设置strVal
的最快方法是什么?
DataCollection.h
extern "C" __declspec(dllexport) void GetContCollection(int CollectionLength,int StrLength, DataContainer** Collection);
typedef struct {
int iValue;
char* strValue;
}DataContainer;
DataCollection.cpp
extern "C" __declspec(dllexport) void GetContCollection(int CollectionLength,int StrLength, DataContainer** Collection)
{
*Collection = (DataContainer*)LocalAlloc(0, CollectionLength * sizeof(DataContainer));
// say i need to get a record from database returning a char array
// and i use current datatype
*DataContainer CurElement = *Collection;
// iteration on each element of the collection
for(int i=0, i< CollectionLength; i++, CurElement++)
{
char* x = getsomeValuefromSystemasChar();
//.... how to assign CurElement->strValue=?
CurElement->strValue =// kind of Allocation is needed or ....just assign
//next, do i have to copy value or just assign it ?
CurElement->strValue = x or strcpy(dest,source)// if copying must take place which function would be the best?
}
}
正确和最优化的设置CurElement
的方法是什么?
对这个问题的评论和编辑已经使这个答案的大部分内容过时了。我把它保留下来,只供任何可能浏览编辑历史的人使用。有效的部分在这个答案的末尾。
如果,正如问题所说,结构体中的所有
char *
都将引用字符串字量,那么您不需要分配内存,或者在分配时采取许多特殊步骤。
字符串字面值具有静态存储时间,因此您只需将其地址分配给指针,就可以了。但是,您不希望任何人意外地写入字符串字面值,因此您通常希望使用指向const
:
typedef struct {
int iValue;
char const * strValue;
} DataContainer;
当你需要分配时,只需分配:
extern "C" __declspec(dllexport) void GetContCollection(int CollectionLength,int StrLength, DataContainer** Collection)
{
// ...
CurElement->strValue = "This is a string literal";
}
您可以(绝对)计算具有静态存储持续时间的字符串字面值,因此毫无疑问这是可行的。因为你只是赋值一个指针,所以它也会很快。
不幸的是,它也有点脆弱——如果有人在这里赋值了字符串字面值以外的东西,它很容易崩溃。
这就引出了下一个问题:你是否真的在处理字符串字面值。尽管您特别询问了字符串字面值,但您所展示的演示代码看起来根本不像是在处理字符串字面值——如果不是,像上面这样的代码将会严重中断。
如果你必须处理这个问题,
我会说只用std::string
。如果您坚持自己这样做,那么您很有可能会产生损坏的东西,并且很少(几乎没有)机会在不损坏任何东西的情况下获得实质性的速度优势。
- 如何在C++中定义静态成员结构
- 使用模板化类的成员结构
- 初始化固定的 C 数组成员结构
- 指向成员结构的指针如何工作
- 如何将此“指针从外部类传递到成员结构
- 导致IAR ARM中出现错误的成员结构位字段元素的Initializer列表初始化
- 映射文件中成员结构的地址
- Visual C++ 模板类成员结构初始化语法糖
- C :初始化成员结构的静态字段的正确方法
- 如何在C 类的初始化器列表中使用未命名结构初始化成员结构
- 从成员结构的成员函数中访问类的成员?
- 模板化类的成员函数无法返回指向成员结构的指针?
- 重载非类型模板结构的成员结构的复制赋值运算符
- 灵气属性传播问题与单成员结构.
- 将具有 int* 成员C++结构编接到 C#
- 复杂的班级成员结构
- 将向量成员(结构)传递给函数
- 成员结构的前向声明
- 重载运算符<<用于模板结构中定义的成员结构
- 返回带有模板化类的类成员结构