initializing a C++ std::istringstream from an in memory buffer?

此生再无相见时 提交于 2019-11-27 04:16:34

Look at std::istrstream it has a constructor

 istrstream( char* pch, int nLength );

This class is sort of depreciated or at least you are normally told to use other classes.
The issue with strstream is that it is more complex to manage the memory of the char* buffer so in general you would prefer stringstream as it does the memory management for you. However in this case you are already managing the memory of the char* so the normal benefit is in this case a cost. In fact in this case strstream does exactly what you want with minimal overhead in code or speed. This is similar to the discussion of ostrsteram by Herb Sutter

It's actually pretty trivial to write a one-shot std::streambuf that uses the buffer in place as the default behaviour of all the virtual functions of std::streambuf does 'the right thing'. You can just setg the read area in construction and underflow and uflow can safely be left to return traits_type::eof() as the end of the initial get area is the end of the stream.

e.g.:

#include <streambuf>
#include <iostream>
#include <istream>
#include <ostream>

struct OneShotReadBuf : public std::streambuf
{
    OneShotReadBuf(char* s, std::size_t n)
    {
        setg(s, s, s + n);
    }
};

char hw[] = "Hello, World!\n";

int main()
{
    // In this case disregard the null terminator
    OneShotReadBuf osrb(hw, sizeof hw - 1);
    std::istream istr(&osrb);

    istr >> std::cout.rdbuf();
}

Boost.IOStreams has a stream that works like a stringstream, but wraps a native array, so you avoid having to copy the data.

std::stringstream always creates its own internal buffer

Untested but perhaps worth a test...

std::stringstream ss;
ss.write( blockPtr, blockLength );
ss.seekg(0);

Then call that setBlob function with ss. Your still have that internal buffer in std::stringstream as jalf already mentioned though.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!