[英]Invalid init of non-const reference of type std::basic_string<char>::const_iterator& from rvalue of type std::basic_string<char>::const_iterator
I'm get the above error when I compile the following MWE on GCC 我在GCC上编译以下MWE时遇到上述错误
#include <string>
void frobnigate( const std::string& str )
{
std::string::const_iterator& iter = str.begin();
}
int main()
{
frobnigate( "all things!!!" );
}
Am I doing something wrong or is this a GCC issue? 我做错了什么还是GCC问题?
Am I doing something wrong or is this a GCC issue? 我做错了什么还是GCC问题?
Yes you are doing something wrong. 是的,你做错了什么。
std::string::begin()
returns a value type ( rvalue , since its a temporary). std::string::begin()
返回一个值类型 ( rvalue ,因为它是临时的)。 But you are trying to initialize a non-const reference from an rvalue which is illegal in C++. 但是你试图从rvalue初始化一个非const引用,这在C ++中是非法的。
You definitely want: 你绝对想要:
std::string::const_iterator iter = str.begin();
Better still: 更好的是:
auto iter = str.begin();
Iterators are cheap to copy and should be used by value, so a reference or const-reference to an iterator is frowned upon. 迭代器的复制成本很低,应该按值使用,因此对迭代器的引用或const引用是不受欢迎的。
You should do this: 你应该做这个:
std::string::const_iterator iter = str.begin();
That is, remove the reference, because begin()
returns a value, not a reference, and you need to manage the lifetime of that iterator (which will be a simple, small, cheap value such as a pointer). 也就是说,删除引用,因为begin()
返回一个值而不是引用,并且您需要管理该迭代器的生命周期(这将是一个简单,小巧,便宜的值,如指针)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.