[英]Dynamic array of struct with string members
我在我的程序中創建了一個動態結構數組,其成員也是字符串。 我對在動態分配的結構內操作字符串的安全行為有一些疑問。 我是否可以像使用普通字符串變量一樣更新或連接字符串? 我是否必須關注結構的分配 memory 的邊界?
為了清楚一點,我有類似以下偽代碼:
首先我有結構聲明
struct myStruct
{
...
int data1;
int data2;
std::string myString1;
std::string myString2;
...
}
然后分配結構
mystruct testStruct*;
testStruct = new mystruct [MAX_DEPTH];
字符串被初始化
for(int i=0; i<MAX_DEPTH; i++)
{
...
testStruct[i].myString1 = "";
testStruct[i].myString2 = "";
...
}
在程序周期中,字符串值被分配和更新
...
testStruct[N].myString1 = "Some text";
...
testStruct[N].myString1 += "Some other text";
...
這里我不確定是否正確處理分配的 memory。
即使在動態分配的結構數組中,這些分配是否正確且安全? 我冒着為 myStruct 變量打破動態分配 memory 的邊界的風險?
謝謝
編輯:我已經更正了 [i] 錯誤地放置在偽代碼中。
對於初學者來說,循環中的表達式不正確
for(int i=0; i<MAX_DEPTH; i++)
{
...
testStruct.myString1[i] = "";
testStruct.myString2[i] = "";
...
}
你的意思是
for(int i=0; i<MAX_DEPTH; i++)
{
...
testStruct[i].myString1 = "";
testStruct[i].myString2 = "";
...
}
但在任何情況下,循環都是多余的,因為當分配結構數組的 memory 時,std::string 類型的對象已經默認初始化。
至於這些說法
testStruct.myString1[N] = "Some text";
...
testStruct.myString1[N] += "Some other text";
然后您需要再次將下標運算符應用於指針testStruct
。 例如
testStruct[N].myString1 = "Some text";
...
testStruct[N].myString1 += "Some other text";
我冒着為 myStruct 變量打破動態分配 memory 的邊界的風險?
如果您將使用大於或等於MAX_DEPTH
和指針testStruct
的索引,那么很明顯會有未定義的行為,
class 字符串的實現方式如下:
namespace std {
template <typename charT,
typename traits = char_traits<charT>,
typename Allocator = allocator<charT>>
class basic_string;
typedef basic_string<char> string;
}
第三個參數是字符串 class 使用的 memory model ,它處理 ZCD69B4957F06CD8298DZ7 的分配和解除分配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.