#include <iostream>
#include <sstream>
usingnamespace std;
class A
{
private:
stringstream ss;
public:
stringstream& getSs()
{
return ss;
}
};
int main()
{
stringstream ss;
A a;
ss = a.getSs(); // compiles when commented, otherwise gets errors
cout << ss.str();
}
First two errors when compiling above example:
C:\>g++ pass_stringstream.cpp
In file included from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\ios:42:0,
from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\ostream:38,
from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\iostream:39,
from pass_stringstream.cpp:1:
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\ios_base.h: In member function '
std::basic_ios<char>& std::basic_ios<char>::operator=(const std::basic_ios<char>
&)':
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\ios_base.h:789:5: error: 'std::i
os_base& std::ios_base::operator=(const std::ios_base&)' is private
operator=(const ios_base&);
^
In file included from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\ios:44:0,
from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\ostream:38,
from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\iostream:39,
from pass_stringstream.cpp:1:
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\basic_ios.h:66:11: error: within
this context
class basic_ios : public ios_base
^
#include <iostream>
#include <sstream>
// using namespace std; // this is a bad habit
class A
{
private:
std::stringstream ss;
public:
std::stringstream& getSs()
{
return ss;
}
};
int main()
{
A a;
std::stringstream &ss = a.getSs();
ss << "Hello, World!";
std::cout << ss.str() << std::endl;
}
You can return a stringstream from a function by value, as long as you are not trying to make a copy:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <sstream>
std::stringstream getSs()
{
std::stringstream ss;
ss << "abc";
return ss; // this is not a copy in C++11
}
int main()
{
std::stringstream ss;
ss = getSs(); // the move assignment mentioned by Catfish above
std::cout << ss.str();
}