[英]Initializing “const std::string” from “std::istringstream”
我正在嘗試解析Key<whitespace>Value
格式的文件。 我正在讀取std::istringstream
對象中的文件行,並std::istringstream
提取Key
字符串。 我想通過使它成為const
來避免意外更改此Key
字符串的值。
我最好的嘗試是初始化一個臨時的VariableKey
對象,然后從中創建一個常量。
std::ifstream FileStream(FileLocation);
std::string FileLine;
while (std::getline(FileStream, FileLine))
{
std::istringstream iss(FileLine);
std::string VariableKey;
iss >> VariableKey;
const std::string Key(std::move(VariableKey));
// ...
// A very long and complex parsing algorithm
// which uses `Key` in a lot of places.
// ...
}
如何直接初始化常量Key
字符串對象?
可以說最好將文件I / O與處理分開,而不是在同一函數中創建const
Key
調用帶有const std::string& key
參數的行處理函數。
就是說,如果您想繼續使用當前模型,則可以簡單地使用:
const std::string& Key = VariableKey;
無需在任何地方復制或移動任何內容。 通過Key
只能訪問const
std::string
成員函數。
您可以通過將輸入提取到函數中來避免“ scratch”變量:
std::string get_string(std::istream& is)
{
std::string s;
is >> s;
return s;
}
// ...
while (std::getline(FileStream, FileLine))
{
std::istringstream iss(FileLine);
const std::string& Key = get_string(iss);
// ...
(將函數的結果綁定到const引用可延長其壽命。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.