当我编译以下 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/