Damian
Damian

Reputation: 4631

Implement move semantics for my own std::vector

How do I implement move schematics for std::vector given the internal fields data, size and capacity? How can I make this thread safe?

#include <utility>

class vec {
public: 
    vec(vec&& o) : size(o.size), capacity(o.capacity), data(std::move(o.data))
    {}

    vec& operator=(vec&& o)
    {
        if (this != &o) {
            size = o.size;
            capacity = o.capacity;
            delete[] data;
            data = o.data;
            o.data = nullptr;
        }
        return *this;
    }

    vec(vec&) = delete;                         // disable copying
    vec& operator=(vec&) = delete;  
    vec& operator=(vec&) const = delete;

    int* data;
    size_t size;
    size_t capacity;
};

Upvotes: 3

Views: 593

Answers (1)

keith
keith

Reputation: 5332

A few points:

  • I don't think you would use std::move on a raw pointer. You would just assign the pointer over using data = o.data and then set the old one to null o.data = nullptr manually.
  • By definition, if you are moving an object, you are making an assumption that no other threads are going to use the object you are moving otherwise you should not be moving it, therefore you would not enforce thread safety in a move assignment operator, you would ensure thread safety in the rest of your code.

Upvotes: 4

Related Questions