c++ - 从 "const std::string"初始化 "std::istringstream"

标签 c++ constants stdstring const-correctness istringstream

我正在尝试解析 Key<whitespace>Value 中的文件格式。我正在读取 std::istringstream 中的文件行对象,我正在提取 Key来自它的字符串。我想避免意外更改此 Key 的值字符串通过使其 const .

我最好的尝试是初始化一个临时的 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 访问。

关于c++ - 从 "const std::string"初始化 "std::istringstream",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33516600/

相关文章:

c++ - 如何使用 vector 来存储形状?

通过引用递归函数传递字符串或流对象时的 C++ 段错误

c++ - 编译器不会为 "const"和 "not-const"函数给出不明确的错误

c++ - 将 zlib 与 const 数据一起使用

c++ - 将 boost::container::boost basic_string 转换为 std::string

c++ - 为什么在 C++ 中将较大函数中的某些功能编写为 lambda?

c++ - 如何实现返回 protected 结构的私有(private)函数

c++ - std::string 中的段错误

c++ - 在 C++ 中将指针变量分配给 const int?

c++ - 将整数转换为 std::pair 接受的 std::string