Reputation: 1125
I'm using stringstream
type variable in my program.
following is code snippet:
stringstream keyvalueStream;
keyvalueStream << // appending some string
somefun(keyvalueStream.str().c_str()); // Passing the char*
keyvalueStream.str(std::string()); // clearing the content of this variable.
Does clearing the content of keyvalueStream
affect the string that I will get in the somefun()
?
Upvotes: 0
Views: 270
Reputation: 109289
The answer to your question depends on what somefun
does with the char const *
you've passed to it, and not on whether or not you clear the contents of the stringstream
.
stringstream::str
returns an std::string
object by value, so it's irrelevant whether you clear the stringstream
contents later on or not.
In the expression
somefun(keyvalueStream.str().c_str());
the returned string
object will be destroyed when the call to somefun
returns. Hence, if somefun
somehow stores the char const *
for later use, you will have undefined behavior. If it operates on the argument however it needs to in the current function call, your code is safe.
Upvotes: 3
Reputation: 11648
Yes. It will.
However you shouldn't even call the c_str()
once you get the underlying str
. It is available till the end of the expression.
From cppreference,
Notes
The copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling c_str() on the result of str() (for example in auto *ptr = out.str().c_str();) results in a dangling pointer.
Upvotes: -1
Reputation: 487
No it wont affect what you have passed into somefun() already. stringstream::str() return by value so you get a copy of the data in your stream, not a reference to it.
Upvotes: 0
Reputation: 18139
When reaching keyvalueStream.str(std::string()); in your snippet somefun(keyvalueStream.str().c_str()); has already finished executing, so no. If that was your question.
Upvotes: 0