move and copy assignments

Jul 7, 2020 at 5:21am
hello there!

i'm currently learning move and copy assignments, and i would value your input and suggestions on taking what i currently have coded into a different direction.

my main question: how do you reset the vector size?

complete code here: https://repl.it/@bondat/hw10
lines 92-113

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  vector &vector::operator=(const vector &rhs) // copy assignment
// make this vector a copy of the rhs (i.e. source)
{
    double *pD = new double[rhs.vsize];            // allocate new space for double[]
    std::copy(rhs.elem, rhs.elem + rhs.vsize, pD); // use std::copy algorithm to copy rhs elements into pD double[]
    delete[] elem;                                 // deallocate old space
    elem = pD;                                     // now that we've copied new, deallocated old elems, reset elem pointer
    // reset vector size
    return *this; // return a self-reference
}

vector &vector::operator=(vector &&rhs) // move assignment
// move rhs (i.e. source) to this vector
{
    delete[] elem;              // deallocate old space
    elem = std::move(rhs.elem); // copy rhs’s elements and size, move implies copying element pointer only

    rhs.elem = 0; // empty the rhs vector
    rhs.elem = nullptr;
    return *this; // return a self-reference
}


when i run the program, the copy constructor is invoked instead of move. How does this result in improved performance? (unless i specifically called that constructor despite having overloaded constructors?)
Last edited on Jul 7, 2020 at 3:00pm
Jul 7, 2020 at 5:40am
my main question: how do you the vector size?

my main answer: size the vector you do how.
Jul 7, 2020 at 5:44am
how do you the vector size?
You simply assign: vsize = rhs.vsize;.
Don't forget to set it to 0 in the move assignment.

Line 18 is redundant.
Jul 7, 2020 at 3:01pm
@dutch ahaha good one! let me edit that.
Jul 7, 2020 at 3:28pm
@coder777 and that will simply reset the vector size :O?
Jul 8, 2020 at 5:43am
that will simply reset the vector size :O?
Yes, you need to copy/move all data. Where's the problem?

You need to set rhs.vsize = 0; in the move assignment.
Topic archived. No new replies allowed.