gpt4 book ai didi

c++ - 类型为“std::string&”的非常量引用的无效初始化

转载 作者:太空宇宙 更新时间:2023-11-04 13:21:36 25 4
gpt4 key购买 nike

我正在尝试使用函数 rtrim() 来修剪字符串在不使用算法的情况下从 C++ 中的字符串 header 获取。
我所做的是检查开始和结束位置是否存在空间,只需使用 isspace() 将其删除即可。但是当我编译时,现在我得到了这个错误:

invalid initialization of non-const reference of type ‘std::string& {aka std::basic_string&}’ from an rvalue of type ‘const char*’

这是我的代码:

#include <iostream>
#include <string>
using namespace std;

string rtrim(string& s) {
size_t i;
for(i = s.length() - 1; i != (size_t)-1; i--) {
if(!(isspace(s[i]))){
break;
}
}
return s.substr(0, i + 1);
}

int main(){
cout << "|" << rtrim(" hello world\t ") << "|" << endl;
}

每当我设置参数如string s = ( "hello world\t ");然后运行 ​​cout << rtrim(s) << endl;似乎在工作,但它不像上面的代码那样工作。有什么建议吗?

最佳答案

以上代码将创建 std::string 的临时对象在堆栈上并将其作为非常量引用传递给函数。这是危险的,因为该函数可能会修改对象(这没有意义)或记住对对象的引用并在对象已被销毁后尝试将其修改到其范围之外。

在你的函数中你实际上不需要 non-const引用,所以只需将参数更改为 const std::string &s它将起作用。

关于c++ - 类型为“std::string&”的非常量引用的无效初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35059752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com