Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
};
like image 572
Damian Avatar asked Jan 20 '26 10:01

Damian


1 Answers

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.
like image 154
keith Avatar answered Jan 23 '26 13:01

keith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!