[英]most optimized approach to assign a char* pointer value (who is a struct member) in struct[]
我正在嘗試制作一個結構的集合,其中一些成員是一種字符串,並且由於字符串處理起來“昂貴”,我試圖通過使用指針來最大化性能。
我盡力從教程中學習,但是 C++ 中有很多不同類型的字符串。
如果值的類型是char*
,設置strVal
的最快方法是什么?
數據集.h
extern "C" __declspec(dllexport) void GetContCollection(int CollectionLength,int StrLength, DataContainer** Collection);
typedef struct {
int iValue;
char* strValue;
}DataContainer;
數據集合.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
的正確和最優化的方法是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
。 如果您堅持自己這樣做,那么您很有可能會產生損壞的東西,並且很少(幾乎沒有)機會在不損壞任何東西的情況下獲得顯着的速度優勢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.