从"std::istringstream"初始化"const std::string"

Initializing "const std::string" from "std::istringstream"

本文关键字:std string const istringstream 初始化      更新时间:2023-10-16

我正在尝试解析一个Key<whitespace>Value格式的文件。我正在读取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;

没有必要在任何地方复制或移动任何东西。只有const std::string成员功能可以通过Key访问。

您可以通过将输入提取到函数中来避免"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);
// ...

(将函数的结果绑定到常量引用可以延长其使用寿命。)