Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to std::move std::string into std::stringstream

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?

like image 642
W.F. Avatar asked May 14 '16 17:05

W.F.


People also ask

Is std::string movable?

Yes, std::string (since C++11) is able to be moved i.e. it supports move semantics.

Is Stringstream deprecated?

The classes in <strstream> are deprecated. Consider using the classes in <sstream> instead.

What does std :: move () do?

std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t . It is exactly equivalent to a static_cast to an rvalue reference type.

Can you pass a Stringstream in C++?

Absolutely! Make sure that you pass it by reference, not by value.


2 Answers

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 of std::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).

like image 176
emlai Avatar answered Oct 09 '22 12:10

emlai


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));
like image 20
Peter Bloomfield Avatar answered Oct 09 '22 12:10

Peter Bloomfield