problems with new / delete

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • verani
    New Member
    • Apr 2010
    • 1

    problems with new / delete

    Hello, i wrote such code.
    Code:
    template <typename T>
    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;
    	}
    But such destructor doesn't work. How should i make this correct?
    Last edited by RedSon; Apr 2 '10, 09:58 PM. Reason: Please use CODE tags!
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    If you really want to do you own memory allocation then:

    Don't construct every member of the array twice. If you want your array members initialised from a supplied default then either allocate each one individually using the default or use the assignment operator to copy the default value into each T.

    Don't destruct every member of your array twice. Just call delete[], it will automatically call all the destructors.

    If you are happy to let someone else do the memory management then just use a vector instead of doing it yourself.

    Comment

    Working...