Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site
Search in forums












SourceForge.net Logo
Home » Developing U++ » U++ Developers corner » Initialization for Buffer<T>
Re: Initialization for Buffer<T> [message #45093 is a reply to message #45090] Sun, 30 August 2015 07:38 Go to previous messageGo to previous message
mirek is currently offline  mirek
Messages: 13975
Registered: November 2005
Ultimate Member
Mindtraveller wrote on Sat, 29 August 2015 18:41
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;


Adding 2 new member variable seems quite wasteful.

However, I am now in process of adding C++11 std::initializer_list to all containers. Without your post, I would probably forgot about Buffer. With C++11, we can now have

Buffer<int> x{ v1, v2, v3 };

x = { v4, v5, v6 };

 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: [Solved] template.h errors when porting from 2010 source to 2012
Next Topic: How to fix this strong behaviore of MSC compiler & temporary value ?
Goto Forum:
  


Current Time: Wed May 08 01:58:05 CEST 2024

Total time taken to generate the page: 0.02056 seconds