将std::stringstream中的std::string引用作为参数传递
Passing std::string reference from std::stringstream as parameter
我使用std::stringstream来构造一个字符串,然后尝试将完成的字符串作为对函数的引用来传递,该函数将std::string&作为参数;。
我在GCC上得到一个编译错误:
../src/so.cpp:22:21: error: invalid initialization of non-const reference of type ‘std::string& {aka std::basic_string<char>&}’ from an rvalue of type ‘std::basic_stringstream<char>::__string_type {aka std::basic_string<char>}’
../src/so.cpp:12:6: error: in passing argument 1 of ‘void myFunc(std::string&)’
make: *** [src/so.o] Error 1
同样的代码在WindowsVS2012上编译,但在我的Linux和Android版本上失败了。这是什么原因?
我可以通过将ss.str()临时分配给一个临时std::字符串,然后通过引用传递该字符串来解决这个问题,但这似乎有点傻。要做到这一点,正确的方法是什么?
#include <iostream>
#include <sstream>
void myFunc (std::string& msg)
{
std::cout << msg << std::endl;
}
int main (void)
{
std::stringstream ss;
ss << "this is a test";
myFunc (ss.str()); // Fails
std::string s = ss.str();
myFunc (s); // Pass
return 0;
}
问题是myFunc
采用了一个非常量左值引用。stringstream::str()
按值返回字符串。在标准C++中,不能将临时值绑定到非常量左值引用,但VS有一个允许这样做的"扩展"。这就是它在VS上编译而不是在其他编译器上编译的原因。
另一方面,const
左值引用可以绑定到右值。因此,修改你的功能将使其工作:
void myFunc (const std::string &msg) { /* as before */ }
更改此项:
void myFunc (std::string& msg)
到此:
void myFunc (const std::string& msg)
// ^^^^^ this will allow temporaries like ss.str()
Visual Studio的某些版本会愚蠢地允许临时绑定到非常量引用。然而,它是危险的,并且不是有效的C++。
由于您没有在myFunc
中写入字符串,因此接受一个常量引用:
void myFunc (std::string const &msg)
{
std::cout << msg << std::endl;
}
这些可以绑定到临时对象
因此,出现此错误的原因是ss.str()返回的是const字符串,而不是字符串。通过创建一个新字符串,您就创建了一个非常量变量,该变量被设置为与ss.str()相同的值,因此可以传递到myFunc()中。按照现有的方式创建一个新字符串可能是修复此问题并仍然按原样使用函数的最简单方法。
相关文章:
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- 为什么我不能将引用作为 std::async 的函数参数传递
- 将 std::type_index 作为模板参数传递给函数模板
- 使用std::move将std::unique_ptr作为qt信号参数传递
- 如何将 std::cin 作为函数的参数传递?
- 使用 std::move 将参数传递给函数,如果该参数声明为按值传递或使用移动操作数 &&,是否有区别?
- 将 std::function* 传递给模板参数
- 将双指针作为参数传递给需要引用 std::vector <double>的函数
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 将参数传递给成员函数,就像使用 std::cout 一样
- 有什么理由C++ 11+ std::mutex 应该声明为全局变量,而不是作为函数参数传递到 std::thread 中
- 类模板的参数太少 "std::pair":在函数中将 std 对作为参数传递
- 如何将函数及其参数传递给成员函数内的 std::async
- 将 istream 转换为 ifstream 时将 std::cin 传递到参数时出现问题
- 将 std::ofstream 对象作为参数传递给类方法
- 我如何将std ::数组作为模板参数传递,其中C 中的元素数量不同
- 是否可以将 std::d eque 的成员函数作为参数传递?
- 使用作为参数传递的 std::intializer_list 初始化 std::数组
- 无法将 std::time_get.get_date 函数作为参数传递给另一个函数
- 从作为模板函数参数传递的 std::function 推导返回和参数类型