On 12/4/2019 5:54 PM, alexo wrote:
> Hello guys,
> I've written this code to get acquainted to assignment operators,
> move constructors and move assignment operators, but I got a
> strange behavior in my code:
> I report it in its fullness because it's 123 lines:
>
> // code starts here
> #include <iostream>
>
> using std::cout;
> using std::ostream;
>
> class Vector
> {
> friend ostream& operator<<(ostream& os, Vector& v)
> {
> for(size_t i=0; i<v.size(); i++)
> os << v[i] << ' ';
>
> return os << '\n';
> }
>
> public:
> Vector(int n=5) : sz(n), data( new int[n])
> {
> for(size_t i=0; i < sz; i++)
> data[i] = 0;
> }
>
> Vector(const Vector& r) : // the copy constructor
> sz(r.size()),
> data( new int[sz] )
> {
> for(size_t i=0; i < sz; i++)
> data[i] = r.data[i];
> }
>
>
> // Vector(const Vector&& r) // the move constructor
Vector(Vector&& r) : // the move constructor
> sz{r.size()},
> data{r.data}
> {
r.sz = 0;
r.data = nullptr;
}
>
> // Vector& operator= (const Vector& r) // the copy assignment
Vector& operator= (Vector& r) // the copy assignment
> {
> delete [] data;
>
> sz = r.size();
> data = new int[sz];
>
> for(size_t i=0; i < sz; i++)
> data[i] = r.data[i];
>
> return *this;
> }
>
> Vector& operator= (const Vector&& r) // the move assignment
> {
> delete [] data;
>
// loose the following
> // data = new int[r.size()];
> data = r.data;
s.sz =
r.sz;
r.data = nullptr;
r.sz = 0;
>
> return *this;
> }
>
> ~Vector() // the destructor
> {
> cout << "deleting memory of array ";
> cout << *this;
>
if (data)
{
The following is a good help:
c++ -std=c++17 -Wall yetAnotherVector.cc && valgrind ./a.out