c++ - 来自 std::basic_string<char>::const_iterator 类型右值的 std::basic_string<char>::const_iterator& 类型的非常量引用的无效初始化

标签 c++ gcc

当我编译以下 MWE 时出现上述错误在 GCC 上

#include <string>

void frobnigate( const std::string& str )
{
    std::string::const_iterator& iter = str.begin();
}

int main()
{
    frobnigate( "all things!!!" );
}

我做错了什么还是 GCC 问题?

最佳答案

Am I doing something wrong or is this a GCC issue?

是的,你做错了什么。

std::string::begin()返回 value type (右值,因为它是临时的)。但是您正在尝试从 rvalue 初始化非常量引用,这在 C++ 中是非法的。

你肯定想要:

std::string::const_iterator iter = str.begin();

更好的是:

auto iter = str.begin();

迭代器的复制成本很低,应该按值使用,因此对迭代器的引用或常量引用是不受欢迎的。

关于c++ - 来自 std::basic_string<char>::const_iterator 类型右值的 std::basic_string<char>::const_iterator& 类型的非常量引用的无效初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43119169/

相关文章:

C++ #ifndef 对于包含文件,为什么头文件全部使用大写?

linux - 如果不是 gcc -static 那么 shell 说 'no such file'

c++ - 当函数没有显式返回值时如何强制编译器错误

c++ - 编译 Fast Light Toolkit (FLTK) 2.0 以与 fastHOG 一起使用

c++ - [[可能]] 和 [[不太可能]] 影响程序汇编的简单示例?

c++ - VS2013 中的 Variadic 模板解析 - 错误 C3520

c++ - 如何告诉 ld 在哪里可以找到 libc

c++ - 是否可以在 OS X 上重新设置 QProgressBar 的样式?

java - 如何解决我的错误LNK2019

c - 如何在 Linux 上调试 C 程序?