sách gpt4 ăn đã đi

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

In lại 作者:太空狗 更新时间:2023-10-29 23:49:18 25 4
mua khóa gpt4 giày nike

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

#include 

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

int chính()
{
frobnigate( "all things!!!" );
}

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

câu trả lời hay nhất

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::const_iterator 类型右值的 std::basic_string::const_iterator& 类型的非常量引用的无效初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43119169/

25 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress