简体   繁体   中英

Strange behavior of stringstream passed by reference

For a project, I'd like to use stringstream to carry on data. To achieve this goal, I have to pass some stringstream as parameter to some function, but when I output the stringstreams, I see something like an address.

The code :

#include <iostream>
#include <sstream>

void doStuff(const std::iostream& msg)
{
    std::cerr << msg << std::endl;
}

int main(void)
{
    doStuff(std::stringstream("av"));
}

The output is : 0xbff4eb40

Can someone explains why I get an address when passing an rvalue ?

And why can't I pass a stringstream by value ?

You probably want to access the string on which the stringstream is storing its data:

void doStuff(const std::stringstream& msg)
{
    std::cerr << msg.str() << std::endl;
}

What is happening in your code is that iostreams contain a void* operator which returns 0 if the stream contains any error or has reached EOF, and another value otherwise. This is usefull for error checking.

When you try to write you stream to std::cerr , the compiler realizes that the stream can be converted to a void* using that operator, and that a void* can be written to a ostream(the operator<< has been defined), and therefore uses it.

Note that i changed the method's signature so that it receives an std::stringstream as an argument, since std::iostream::str is not defined(this method is only available on string streams).

You get an address because it (like other streams) has a conversion to void * (which is primarily useful as a Boolean, to see whether reading/writing the stream has failed).

You can't pass it by value, because streams (again, in general, not just stringstreams) don't support copying and/or assigning.

To print the content of the stream, you could do something like:

void dostuff(std::iostream &msg) { 
    std::cerr << msg.rdbuf() << "\n";
}

Edit: Here's a complete demo program:

#include <iostream>
#include <sstream>

void show(std::ostream &os) { 
    std::cout << os.rdbuf() << "\n";
}


int main(){ 
    std::stringstream test("whatever");
    show(test);
    return 0;
}

When I execute it, the output I get is the expected "whatever".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM