如何重用ostringstream?

我想清除并重用ostringstream(和底层缓冲区),这样我的应用程序就不必做太多分配了。如何将对象重置为其初始状态?



明月笑刀无情
浏览 485回答 3
3回答

慕田峪9158850

如果要以某种方式清除缓冲区,使其在首次使用之前被清除,则需要先使用MSVC向缓冲区中添加一些内容。struct Foo {&nbsp; &nbsp; std::ostringstream d_str;&nbsp; &nbsp; Foo() {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; d_str << std::ends;&nbsp; &nbsp;// Add this&nbsp; &nbsp; }&nbsp; &nbsp; void StrFunc(const char *);&nbsp; &nbsp; template<class T>&nbsp; &nbsp; inline void StrIt(const T &value) {&nbsp; &nbsp; &nbsp; &nbsp; d_str.clear();&nbsp; &nbsp; &nbsp; &nbsp; d_str.seekp(0);&nbsp; // Or else you'll get an error with this seek&nbsp; &nbsp; &nbsp; &nbsp; d_str << value << std::ends;&nbsp; &nbsp; &nbsp; &nbsp; StrFunc(d_str.str().c_str());&nbsp; // And your string will be empty&nbsp; &nbsp; }};

守着星空守着你

考虑一下用例,其中代码遍历输入数据,写入ostringstream(基于读取的数据),然后必须ostringstream不时写入某个地方(例如,在读取某些字符序列之后)内置的字符串,然后开始建立一个新的字符串。
打开App,查看更多内容
随时随地看视频慕课网APP