jeudi 5 mai 2016

What is the Bare Minimum for a Class which Manages a Resource?

So suppose I've written a class which is essentially a std::vector. That means I've written code that looks like this:

class my_vector {
public:
    my_vector(size_t count) :
    memory(new int[count]), size_of_memory(count)
    {
    }

    my_vector(const my_vector & v) :
    my_vector(v.size_of_memory)
    {
        std::copy(v.memory, v.memory + size_of_memory, memory);
    }

    void swap(my_vector & v) noexcept {
        std::swap(v.memory, memory);
        std::swap(v.size_of_memory, size_of_memory);
    }

    my_vector(my_vector && v) {
        swap(v);
    }

    my_vector & operator=(my_vector v) {
        swap(v);
        return *this;
    }

    ~my_vector() {
        delete[] memory;
    }

    int & operator[](size_t index) {
        return memory[index];
    }

    const int & operator[](size_t index) const {
        return memory[index];
    }
private:
    int * memory;
    size_t size_of_memory;
};

I have two questions about this code:

  1. Can this code cause a Memory Leak? I've tried to cover all the RAII bases as best as I can, but I'm still pretty new to C++, all things considered.
  2. Are there any design considerations/mistakes I'm not accounting for? Is my swap function designed the best way it can be, or should it have a different signature? Same question for my assignment operator.

EDIT: this is not about the Copy-And-Swap Idiom. I know what it is, and my concerns extend beyond simply "why do we need this". I'm looking for corner cases and issues with the specific manner in which I've written my code.

Aucun commentaire:

Enregistrer un commentaire