Pregunta

I'm licking my wounds from Memory Error with std:ostringstream and -std=c++11?, and I have a related question.

If the following returns a temporary so that reserve has no effect and the char* is not valid:

ostringstream oss;
oss.str().reserve(96);

// populate oss

const char* ptr = oss.str().c_str();
// do something with ptr

Then how does the following clear the ostringstream (from How to reuse an ostringstream?):

oss.clear(); oss.str("");

I understand clear() will reset the stream's flags; but as I now understand str("") will operate on a temporary and not the underlying string.

So how does str("") reset the stream?

¿Fue útil?

Solución

These are different functions.

oss.str() (without parameters) returns a copy to the stream's underlying string, but oss.str("") sets its underlying string to the value you passed (here an empty string: "").

So calling both clear() and str("") on a std::stringstream actually kind of "resets" it.

Notice the two signatures on cppreference

Otros consejos

Calling str with no argument returns a copy of the internal string object. That's why it's a temporary object. Calling str with a string argument sets the value of the internal string object. It doesn't work on a temporary object.

It seems like you're thinking of it like this:

oss.str() = "";

But that's not what it is. You're passing "" to the str function so that it can assign it to the internal string.

It's no different to any other getter/setter combination. If you have getX(), it typically gets you a copy of some member of the class you're calling it on. If you have setX(x), it typically sets the value of that member. In this case, they're just both called str, but one takes an argument and the other doesn't.

From this std::ostringstream::str reference:

Parameters

new_str - new contents of the underlying string

It can be used to get the string, or to set the string to the string provided by the functions argument.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top