Home » Developing U++ » U++ Developers corner » Initialization for Buffer<T>
Initialization for Buffer<T> [message #45090] |
Sat, 29 August 2015 18:41 |
Mindtraveller
Messages: 917 Registered: August 2007 Location: Russia, Moscow rgn.
|
Experienced Contributor |
|
|
Buffer<T> is known as replacement for C-style arrays. So I guess it needs some way to fill it as easy as possible (like we initialize arrays in C). So here is my proposal with little additions:
template <class T>
class Buffer : Moveable< Buffer<T> > {
size_t size;
mutable T *ptr;
int insertI;
public:
operator T*() { return ptr; }
operator const T*() const { return ptr; }
T *operator~() { return ptr; }
const T *operator~() const { return ptr; }
Buffer<T> & Alloc(size_t _size) { Clear(); ptr = new T[_size]; size = _size; return *this; }
Buffer<T> & Alloc(size_t _size, const T& in) { Clear(); ptr = new T[_size]; size = _size; Fill(ptr, ptr + size, in); return *this; }
void Clear() { if(ptr) delete[] ptr; ptr = NULL; insertI = 0; size = 0; }
size_t GetCount() { return size; }
Buffer() { Init(); ptr = NULL; }
Buffer(size_t size) { Init(); ptr = new T[size]; }
Buffer(size_t size, const T& init) { Init(); ptr = new T[size]; Fill(ptr, ptr + size, init); }
~Buffer() { if(ptr) delete[] ptr; }
void Init() { size = 0; insertI = 0; }
void operator=(Buffer rval_ v) { if(ptr) delete[] ptr; ptr = v.ptr; v.ptr = NULL; }
Buffer<T> & operator<< (const T &in){ ptr[insertI++] = in; return *this; }
Buffer(Buffer rval_ v) { ptr = v.ptr; v.ptr = NULL; size = v.size; v.size=0; insertI = 0; }
};
// Usage:
// buffer.Alloc(3) << v1 << v2 << v3;
[Updated on: Sat, 29 August 2015 23:10] Report message to a moderator
|
|
|
Goto Forum:
Current Time: Sat Sep 21 03:07:30 CEST 2024
Total time taken to generate the page: 0.03184 seconds
|