Search code examples
c++pointersmemcpy

Could I use memcpy to the pointer which I new it before?


for example, I try to write my own vector, so I just write its assign function like this

template <typename T>
void Vector<T> :: assign(T *start, T *end)
{
    if (end - start > _capacity)
    {
        resize(end - start);
    }
    _size = end - start;
    delete []ptr;
    ptr = new T[_capacity];
    memcpy(ptr, start, end - start);
}

I have new the pointer ptr before, but I can copy all I what between the pointer start and end

why? Thankyou very much.


Solution

  • First problem is that this only works for simple types (read POD).
    Anything with a constructor/destructor needs to have them called.

    Second this is not exception safe.
    It does not even provide the basic guarantee let a lone the strong guarantee.

    You need to do all exception unsafe work before modifying the object. This means the new must be done before you modify the object (and definitely before the free). Otherwise you could potentially throw leaving the object in an invalid state (that might not seem bad, but what if you catch the exception and continue you now have an object that contains a pointer to released memory).

    So even if you use std::copy() you still have done the wrong thing.
    Personally I think the suggestion of std::copy() is a red herring. It will copy the data correctly but you are still writing your method badly. You need to use a twist on the copy and swap idium.

    template <typename T>
    void Vector<T> :: assign(T *start, T *end)
    {
        Vector<T> tmp(start, end);  // construct a temp object that allocates the memory.
    
    
    
        swap(tmp);                  // Swap the current object and the tmp objects data.
                                    // When the tmp object goes out of scope it will delete
                                    // what was the current objects data
    
    }