使用智能指针管理一段buffer

#pragma once

#ifdef __cplusplus

#include <memory>
#include <cstdint>
#include <cstddef>

#else

#include "stdint.h"
#include "stddef.h"

#endif // __cplusplus

namespace easy_sa {
	struct BufferBytes
	{
		uint8_t const* data;
		size_t size;

		std::shared_ptr<uint8_t> holder;
		
		static BufferBytes make(size_t sz) {
			BufferBytes bb;
			bb.holder = std::shared_ptr<uint8_t>(new uint8_t(sz),
				[](uint8_t* ptr) { delete[] ptr; });
			bb.size = sz;
			bb.data = bb.holder.get();
			return bb;
		}
		static BufferBytes make(const uint8_t* buf, size_t sz) {
			BufferBytes bb;
			bb.data = buf;
			bb.size = sz;
			return bb;
		}

	};
	
}
posted @ 2022-03-28 23:38  cyssmile  阅读(80)  评论(0)    收藏  举报