I wrote this code.
The constructor works normally, but in the destructor I get “Windows has triggered a breakpoint.” How should I correct this?
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 = ::new T[capacity]; //memory allocating
for(T* p = mem_ptr; p < mem_ptr + capacity * sizeof(T); p += sizeof(T)) {
::new (p) T (default_value); //initialization
}
}
~CyclicalArray() {
for(T* p = mem_ptr + sizeof(T); p < mem_ptr + capacity * sizeof(T); p += sizeof(T)) {
p->~T();
}
delete[] mem_ptr;
}
If you’re going to perform placement new, you need to do it on raw memory. Something like:
Otherwise you’ll call the T destructor twice on the same object memory (not a good thing to do).
Also, since your
ppointers are of typeT*, you can perform simple increment/decrements on it – the compiler will deal with thesizeof(T)issue as a normal course of pointer arithmetic.Finally, strictly speaking you should destroy the array elements in descending order (the opposite of construction).
I hope this catches most or all the bugs.
You might really want to consider using something like std::vector as the store. An example using
std::vector<>follows (with a few other syntax fixes). I’m not sure if your class would really need a copy of thedefault_valueor thehead_index– I left them in assuming that you plan to use them in other methods:Note how much simpler the constructor and destructor are, since all the complexity of your first class is managed by
std:vector.