In all standard containers like std::map
or std::vector
there is a move constructor and a move assignment to avoid copying. I want to build my own Wector
class with the same functionalities. My class declaration looks as follows:
class Wector{
public:
~Wector();
Wector();
Wector(std::size_t s);
Wector(std::size_t s, const double nr);
Wector(const std::initializer_list<double> il);
//copy constructor
Wector(const Wector & w);
//move constructor
Wector(Wector&& w);
std::size_t size() const;
double* begin(); // iterator begin
double* end(); // iterator end
const double* begin() const; // const iterator begin
const double* end() const; // const iterator
const double& operator[](std::size_t i)const;
double& operator[](std::size_t i);
Wector& operator=(const Wector& w);
//move assignment
Wector& operator=(Wector&& w);
private:
std::size_t wsize;
void swap(Wector& w);
double *element; // double *element = new double[s]
};
To implement the move-assignment and constructor I need a customer swap
.
//move constructor
Wector::Wector(Wector&& w)
: Wector()
{
swap(w);
}
//move assignment
Wector& Wector::operator=(Wector&& w){
swap(w);
return *this;
}
But I have no idea how to implement the swap
function without having direct access to the data element
and without copying with help of the iterators.
void Wector::swap(Wector& v){
std::swap(wsize, v.size());
double * temp = new double[v.size()];
std::copy(w.begin(), w.end(), temp);
std::swap(element, temp);
delete [] temp; //edited
}
Does anybody know how it is implemented in the case of std::vector
?