All About Performance

and other stuff by Taras Glek

Where Is the Sanity in the C++ Std Library?

Dear lazyweb,

Please explain to me why the following code works the way it does. From looking at the following code and stringstream::str(), stringstream::str(string) docs the behavior of the following code does not make sense to me.

1
2
3

#include <sstream>
#include <iostream>

using namespace std;

int main(int argc, char**) { stringstream ss(“foo”); cout << ss.str() << endl; ss << “bar”; cout << ss.str() << endl; ss << “more”; cout << ss.str() << endl; }

Why is doing << after str(string) causing this stringstream to loose the initialization string? What possible API usecase would justify such behavior?

For the curious, output is:

foo bar barmore

It seems that the only sensible way to use stringstream is to do ss.str(“”) unless you want to have your initial data reset for no reason. In that case why add a weird method overload instead of a .reset() method.

Update: Note that stringstream ss(“foo”) is equivalent to stringstream ss; ss.str(“foo”);

Comments