move semantics/constructor

discussion pertains to this video:
https://www.youtube.com/watch?v=7LxepUEcXA4

I'm just starting on move semantics, r-values, etc. I get most of this video until the last 45 seconds or so when he is adding an empty move constructor. What does that accomplish? He seems to be saying that this allows the compiler to choose whatever constructor version works best for the assignment operator, (r-value vs l-value) but I'm not really following how it works.

Thanks for any help


It's not supposed to be empty. He just left it out in the video. It would probably have looked something like this:

1
2
3
4
5
6
7
DynArray(DynArray&& other)
:	m_size(other.m_size), 
	m_data(other.m_data)
{
	other.m_size = 0;
	other.m_data = nullptr;	
}


So when the copy assign operator is called the parameter (DynArray copy) will be constructed using the copy constructor or the move constructor depending on what is appropriate.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
DynArray a(20);
DynArray b(30);

// This will construct copy in operator= using the 
// copy constructor because b is not a r-value, and we 
// don't want b to be modified by the move constructor.
a = b; 

// This will construct copy in operator= using the 
// move constructor because DynArray(70) is a r-value,
// and it doesn't matter if it's modified by the move 
// constructor because it will never be used elsewhere anyway. 
// If the move constructor was not declared it would have
// used the copy constructor which would have been slower
// because it copies the whole m_data array
a = DynArray(70);
Last edited on
OK, THAT would make more sense to me. As I understand 'move', the thing you are moving from, is still useable, and valid, but in loose english, it is 'empty'', because you 'moved' the data elsewhere, which is what setting other.m_size to 0 and in particular, other.m_data to nullptr does. Does that sound right? I just saw this move constructor that didn't do anything...
Yes that sounds about right.
Topic archived. No new replies allowed.