From 7d5f055547e70fa93ee9ac944e62f8d657b9dc55 Mon Sep 17 00:00:00 2001 From: chai Date: Fri, 19 Oct 2018 08:36:44 +0800 Subject: =?UTF-8?q?*=E4=BF=AE=E6=94=B9=E6=96=87=E4=BB=B6=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/libjin/Common/je_array.hpp | 86 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 src/libjin/Common/je_array.hpp (limited to 'src/libjin/Common/je_array.hpp') diff --git a/src/libjin/Common/je_array.hpp b/src/libjin/Common/je_array.hpp new file mode 100644 index 0000000..eadd36f --- /dev/null +++ b/src/libjin/Common/je_array.hpp @@ -0,0 +1,86 @@ +#ifndef __LIBJIN_COMMON_ARRAY_H +#define __LIBJIN_COMMON_ARRAY_H + +namespace jin +{ + /* 自动释放堆内存的在栈上创建的动态数组 */ + template + class Array + { + public: + Array() : length(0), data(nullptr) {} + + Array(int l) + { + length = l; + data = new T[l]; + } + + ~Array() + { + delete[] data; + length = 0; + } + + T* operator &() + { + return data; + } + + T& operator[](int index) + { + return data[index]; + } + + /* 绑定内存 */ + void bind(T* d, int len) + { + if (data != nullptr) + delete data; + data = d; + length = len; + } + + void add(T v) + { + int len = length + 1; + T* d = new T[len]; + memcpy(d, data, size()); + d[length] = v; + bind(d, len); + } + + int size() + { + return sizeof(T) * length; + } + + int count() + { + return length; + } + + private: + /// + /// http://blog.jobbole.com/106923/ + /// new 堆内存创建对象过程 + /// 1. 调用 new 分配内存 + /// 2. 调用构造函数 + /// + /// new, delete方法用于分配和释放内存,不负责构造和析构 + /// + void* operator new(size_t t); + + /// + /// Disable delete. + /// + void operator delete(void* ptr); + + T * data; + unsigned int length; + + }; + +} // namespace jin + +#endif \ No newline at end of file -- cgit v1.1-26-g67d0