If you intend to perform a new placement, you need to do this in raw memory. Sort of:
template class CyclicalArray { private: T* mem_ptr; public: CyclicalArray(size_t capacity, const T& default_value) { this->default_value = default_value; this->capacity = capacity; head_index = 0; mem_ptr = reinterpret_cast<T*>( ::new char[capacity * sizeof(T)]);
Otherwise, you will call the T destructor twice in the same memory of the object (not very good).
In addition, since your p pointers are of type T* , you can perform simple increments / reductions on it - the compiler will treat the sizeof(T) problem as a regular pointer arithmetic course.
Finally, strictly speaking, you must destroy the elements of the array in descending order (the opposite of construction).
I hope this catches most or all of the bugs.
You might want to use something like std :: vector as storage. An example using std::vector<> follows (with several other syntax fixes). I'm not sure if your class really needs a copy of default_value or head_index - I left them under the assumption that you plan to use them in other methods:
#include <vector> template <typename T> class CyclicalArray { private: std::vector<T> backing_store; T default_value; size_t head_index; public: CyclicalArray(size_t capacity, const T& def_val) : backing_store(capacity, def_val), default_value( def_val), head_index(0) { } ~CyclicalArray() {} };
Note how much easier the constructor and destructor are, since all the complexity of your first class is controlled by std:vector .
source share