Game Development Reference
In-Depth Information
Listing 12-5. The Player Move Constructor
Player(Player&& tempPlayer)
{
m_pCurrentRoom = tempPlayer.m_pCurrentRoom;
m_name = tempPlayer.m_name;
tempPlayer.m_pCurrentRoom = nullptr;
m_name.clear();
}
The double reference symbol in a move constructor means that the reference being passed in is an
rvalue reference . rvalue references occur when passing temporary objects into methods. This occurs
often when using STL containers, which we'll be looking at in Part 3 of this topic. It's also important
to clear the data from the object passed into the move constructor, and you'll see why this is the
case when we look at memory management in Part 5. A move assignment operator can also be
added to your classes. Listing 12-6 shows how to do this.
Listing 12-6. A Move Assignment Operator
Player& operator=(Player&& tempPlayer)
{
if (this != &tempPlayer)
{
m_pCurrentRoom = tempPlayer.m_pCurrentRoom;
m_name = tempPlayer.m_name;
tempPlayer.m_pCurrentRoom = nullptr;
m_name.clear();
}
return *this;
}
Summary
This short chapter has introduced you to the methods that can be added to classes to allow you to
pass data around in your programs. These are not particularly useful as stand-alone procedures,
but they will be very useful in the next part of this topic when we look at the STL. The STL provides
us with containers to store many objects in data structures and we will be using copy constructors,
assignment operators, and move semantics liberally throughout that entire part of the topic.
You have seen how copy constructors allow you to make copies of classes. This occurs most often
when passing objects into functions by value; however, you will usually be satisfied with passing
most objects by a const reference to avoid the cost of invoking the copy constructor. You've
also seen how you can overload assignment operators to copy data from one object to another
preexisting object. Finally, you saw how move semantics can be added to your classes. You'll see
better how these are useful later in this topic.
 
Search WWH ::




Custom Search