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

hiz5n14c  于 2023-01-06  发布在  其他
关注(0)|答案(2)|浏览(129)
#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的底层字符串对象?

piv4azn7

piv4azn71#

标准规定std::ostringstream::str() returns a copy .
避免这种复制的一种方法是实现另一个std::streambuf派生类,直接公开字符串缓冲区。

#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';
}
6pp0gazn

6pp0gazn2#

从C++20开始,你可以。

std::move(oss).str()

相关问题