在struct[]中分配char*指针值(结构成员)的最优化方法

most optimized approach to assign a char* pointer value (who is a struct member) in struct[]

本文关键字:成员 结构 方法 最优化 指针 struct 分配 char      更新时间:2023-10-16

我试图使结构的一些成员是一种类型的字符串的集合,因为字符串是'昂贵的'来处理我试图通过使用指针来最大化性能。

我尽我最大的努力从教程中学习,但是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。如果您坚持自己这样做,那么您很有可能会产生损坏的东西,并且很少(几乎没有)机会在不损坏任何东西的情况下获得实质性的速度优势。