outstream输出流结构

本文介绍了一个使用C++实现的自定义输出流类,该类支持写入和读取字符串数据,并具备自动扩容功能。通过示例展示了如何使用此类进行数据的写入和读取操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdint.h>
#include <cassert> 
#include <iostream>
#include <string>
#include <algorithm>
#define SAFE_FREE(x) do { if ((x) != nullptr) { free((x)); (x) = nullptr;} } while (0)
class out_stream {
public:
    out_stream() {
        data_ = nullptr;
        size_ = 0;
        capacity_ = 0;
    }
    out_stream(const out_stream &) = delete;
    out_stream & operator = (const out_stream &) = delete;
    virtual ~out_stream() {
        SAFE_FREE(data_);
        size_ = 0;
        capacity_ = 0;
    }
public:
    void write(const char *input, size_t len) {
        int remain = capacity_ - size_;
        if (remain < len) {
            enlarge(size_ + len);
        }
        std::copy(input, input + len, data_ + size_);
        size_ += len;
    }
    void read(std::string &str) {
        str.assign((char *)data_, size_);
    }
private:
    void enlarge(int new_size) {
        if (new_size <= capacity_) {
            return;
        }
        uint8_t *new_data = nullptr;
        if (data_ != nullptr) {
            new_size = std::max(capacity_ << 1, new_size);
            new_data = (uint8_t *)malloc(sizeof(uint8_t) * new_size);
            assert(new_data != nullptr);
            std::copy(data_, data_ + size_, new_data);
            SAFE_FREE(data_);
        }
        else {
            new_size += 32;
            new_data = (uint8_t *)malloc(sizeof(uint8_t) * new_size);
        }
        data_ = new_data;
        capacity_ = new_size;

    }
private:
    uint8_t *data_;
    int size_;
    int capacity_;
};
int main() {
    out_stream stream;
    stream.write("AAAA", 4);
    std::string str;
    stream.read(str);
    std::cout << str << std::endl;

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值