Reputation: 4631
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
Reputation: 5332
A few points:
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.Upvotes: 4