如何移动 std::ostringstream 的底层字符串对象?


#include <sstream>
#include <string>
using namespace std;
template<typename T>
string ToString(const T& obj)
{
    ostringstream oss;
    oss << obj;
    //
    // oss will never be used again, so I should
    // MOVE its underlying string.
    //
    // However, below will COPY, rather than MOVE, 
    // oss' underlying string object!
    //
    return oss.str();
}

如何移动std :: ostringstream的基础字符串对象?

标准说std::ostringstream::str()返回A copy

避免此副本的一种方法是实现另一个std::streambuf派生类,该类别直接曝光字符串缓冲区。boost.iostreams使这个非常琐碎:

#include <boost/iostreams/stream_buffer.hpp>
#include <iostream>
#include <string>
namespace io = boost::iostreams;
struct StringSink
{
    std::string string;
    using char_type = char;
    using category = io::sink_tag;
    std::streamsize write(char const* s, std::streamsize n) {
        string.append(s, n);
        return n;
    }
};
template<typename T>
std::string ToString(T const& obj) {
    io::stream_buffer<StringSink> buffer{{}};
    std::ostream stream(&buffer);
    stream << obj;
    stream.flush();
    return std::move(buffer->string); // <--- Access the string buffer directly here and move it.
}
int main() {
    std::cout << ToString(3.14) << 'n';
}

以来C 20您可以。

std::move(oss).str()

最新更新