2015-11-04 133 views
2

我试图解析一个格式为Key<whitespace>Value的文件。我正在读取std::istringstream对象中的文件行,并从中提取Key字符串。我想要避免意外地更改Key字符串的值,使其为const从“std :: istringstream”初始化“const std :: string”

我最好的尝试是初始化一个临时的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字符串对象?

回答

3

将文件I/O从处理中分离出来,而不是在同一个函数中创建constKey可能更好 - 调用一个采用const std::string& key参数的行处理函数。

这就是说,如果你想继续使用当前的模型,你可以简单地使用:

const std::string& Key = VariableKey; 

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

2

可以通过提取输入到一个函数避免“划痕”变量:(绑定函数的结果到const引用延伸其寿命)

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); 

// ... 

相关问题