简体   繁体   English

从std :: ostringstream重定向到另一个std :: ostringstream

[英]Redirect from a std::ostringstream to another std::ostringstream

I need write data from some std::ostringstream to another std::ostringstream . 我需要将一些std::ostringstream数据写入另一个std::ostringstream Of course, I can use str() function 当然,我可以使用str()函数

std::ostringstream in;
std::ostringstream out;

in << "just a test"; // it's just an example. I mean that stream in is filled somewhere
...
out << in.str();

I'd like to know if there is more direct way to do the same. 我想知道是否有更直接的方法来做同样的事情。

You can reassign the associated buffers: 您可以重新分配关联的缓冲区:

os2.rdbuf(os1.rdbuf());

That effectively aliases the ostream. 这有效地使ostream混淆。

In fact, you can even construct ostream directly from a streambuffer pointer IIRC 实际上,您甚至可以直接从streambuffer指针IIRC构造ostream


Similarly, you can append the whole buffer to another stream without reassigning: 同样,您可以将整个缓冲区附加到另一个流而不重新分配:

std::cout << mystringstream.rdbuf(); // prints the stringstream to console

The copy assignment operator/copy constructor are deleted. 复制赋值运算符/复制构造函数将被删除。 However, you can use the member function swap (C++11), or std::swap , to swap the content. 但是,您可以使用成员函数swap (C ++ 11)或std::swap来交换内容。 Or, you can use the move assignment operator (C++11) to move one into the other. 或者,您可以使用移动赋值运算符(C ++ 11)将一个移动到另一个。 This solution works only in the case when you don't care about the content of the source stringstream. 此解决方案仅适用于您不关心源字符串流的内容的情况。

Example: 例:

out = std::move(in); // C++11
out.swap(in); // C++11
std::swap(out, in); 

PS: I just realized that g++ does not compile any of the above lines (it seems it doesn't support move/swap for ostringstream), however, clang++ compiles it. PS:我刚刚意识到g ++没有编译上面的任何一行(似乎它不支持ostringstream的move / swap),但是,clang ++编译它。 According to the standard (27.8.4), swap/move should work. 根据标准(27.8.4),交换/移动应该有效。 See C++ compiler does not recognize std::stringstream::swap 请参阅C ++编译器无法识别std :: stringstream :: swap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM