Home > Backend Development > C++ > body text

How can I create an input stream from immutable memory?

Susan Sarandon
Release: 2024-11-09 04:47:01
Original
483 people have browsed it

How can I create an input stream from immutable memory?

Constructing an Input Stream from Immutable Memory

In software development, it's often necessary to read data from memory buffers without copying or altering their contents. One such scenario is when the data is stored in a constant character pointer (const char*). To enable convenient reading from such buffers, creating an input stream is a viable solution.

A custom stream buffer can facilitate the creation of an input stream from immutable memory. Here's how to implement it:

#include <streambuf>
#include <istream>

struct membuf : std::streambuf {
    membuf(char const* base, size_t size) {
        char* p(const_cast<char*&>(base));
        this->setg(p, p, p + size);
    }
};

struct imemstream : virtual membuf, std::istream {
    imemstream(char const* base, size_t size)
        : membuf(base, size), std::istream(static_cast<std::streambuf*&>(this)) {
    }
};
Copy after login

The const_cast&> () in the stream buffer is necessary because the stream buffer is not modifying the data, but the interface requires a char.

Once the stream buffer is created, you can use it to initialize an input stream and read data from the buffer:

imemstream in(data, size);
int x;
float y;
std::string w;
in >> x >> y >> w;
Copy after login

The above is the detailed content of How can I create an input stream from immutable memory?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template