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

标签 c++ performance c++11 move-semantics rvalue-reference

#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();
}

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

最佳答案

标准说 std::ostringstream::str() returns 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++ - 如何 move std::ostringstream 的底层字符串对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41035246/

相关文章:

c++ - C 结构中的总线错误

c++ - 我需要分发哪个版本的可再发行版本?

c++ - std::ostream 到 QString?

java - 在 Oracle 端或应用程序本身执行查询过滤

java - 如何使用 BigIntegers 提高 charAt 的性能?

c++ - 我什么时候会在基类中默认(而不是删除)复制和移动操作

C++ Vector Sort 方法编译失败,返回预期的表达式

c++ - Raspberry pi (QT C++) 和 Arduino (Arduino IDE) 之间的通信

vb.net - 在 VB.Net 中,使用静态定义的常量(与等效的字符串文字相比)是否可以提高效率?

c++ - std::upper_bound 和 std::lower_bound 的不同比较签名