In the c++ reference I do not see a std::stringstream
constructor accepting rvalue reference of std::string
. Is there any other helper function to move string to stringstream without an overhead or is there a particular reason behind making such limitation?
Is there a way to std::move std::string into std::stringstream
Asked Answered
Since C++20 you can move a string
into a stringstream
: cppreference
Old answer for pre-C++20:
I do not see a
std::stringstream
constructor accepting rvalue reference ofstd::string
That's right. Even the str
setter doesn't utilize move semantics, so moving a string into stringstream
is not supported (not in the current standard, but hopefully in the next one).
Hopefully there are some good people creating proposals making c++ more straightforward :) –
Cash
You'll be able to move a string into a string-stream in C++20.
Move semantics are supported by the constructor:
std::string myString{ "..." };
std::stringstream myStream{ std::move(myString) };
It can also be done after construction by calling str()
:
std::string myString{ "..." };
std::stringstream myStream;
myStream.str(std::move(myString));
© 2022 - 2024 — McMap. All rights reserved.
str()
is aconst
function; it's not allowed to modify thestringstream
's data at all. It would be very easily to create APIs that would permit the moving of string data without requiring it. After moving into the stream, the string would be "valid-but-unspecified". After moving from the stream, the stream would be "valid-but-unspecified." – Pluckypath
classes, but nobody has even considered allowingfstream
s to take them as filenames. – Plucky