[英]Initializing “const std::string” from “std::istringstream”
I'm trying to parse a file which is in Key<whitespace>Value
format. 我正在尝试解析
Key<whitespace>Value
格式的文件。 I'm reading the file lines in an std::istringstream
object, and I'm extracting a Key
string from it. 我正在读取
std::istringstream
对象中的文件行,并std::istringstream
提取Key
字符串。 I want to avoid accidentally changing the value of this Key
string by making it const
. 我想通过使它成为
const
来避免意外更改此Key
字符串的值。
My best attempt was initializing a temporary VariableKey
object, and then making a constant one out of it. 我最好的尝试是初始化一个临时的
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.
// ...
}
How do I directly initialize a constant Key
string object? 如何直接初始化常量
Key
字符串对象?
It's arguably better to separate file I/O from processing, and instead of creating a const
Key
inside the same function - call a line-processing function that takes a const std::string& key
parameter. 可以说最好将文件I / O与处理分开,而不是在同一函数中创建
const
Key
调用带有const std::string& key
参数的行处理函数。
That said, if you want to continue with your current model, you can simply use: 就是说,如果您想继续使用当前模型,则可以简单地使用:
const std::string& Key = VariableKey;
There's no need to copy or move anything anywhere. 无需在任何地方复制或移动任何内容。 Only
const
std::string
members functions will be accessible via Key
. 通过
Key
只能访问const
std::string
成员函数。
You can avoid the "scratch" variable by extracting the input into a function: 您可以通过将输入提取到函数中来避免“ 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);
// ...
(Binding the function's result to a const reference extends its lifetime.) (将函数的结果绑定到const引用可延长其寿命。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.