📖
Go C++
  • Introduction
  • Chapter 1: What You Must Know First
    • Virtual Address Space of Process: Memory Partition and Layout
    • Function Call: Stack Frame
    • Program Compiling and Linking
  • Chapter 2: C++ Basics Improvement
    • Default Parameters
    • Inline Function
    • Function Overloading
    • new and delete
    • const and Pointers
    • References in Detail
  • Chapter 3: Object-Oriented Principles
  • Class and Object
  • Constructor and Destructor
  • Shallow Copy and Deep Copy
  • Initializer List
  • Various Member Functions
  • Pointer to Class Members
  • Chapter 4: Template Programming
  • Function Templates
  • Class Templates
  • Memory Allocators
  • Chapter 5: Operator Overloading
    • Operator Overloading
    • Introduction to Iterators
    • Issues of Iterator Invalidation
    • More about new and delete
    • Overloading of new and delete: Object Pool
  • Chapter 6: Inheritance and Polymorphism
    • Look inside Inheritance
    • More about Inheritance
    • Virtual Functions, Static Binding and Dynamic Binding
    • More about Virtual Functions
    • Understanding Polymorphism
    • Abstract Classes
    • Frequently Asked Interview Questions: Polymorphism
  • Chapter 7: Multiple Inheritance
    • Virtual Inheritance and Virtual Base Classes
    • Diamond Problem
    • Four Kinds of Type Conversions
  • Chapter 8: Standard Template Library
    • Sequence Containers
    • Container Adaptors
    • Associative Containers
    • More about Iterators
    • Function Objects
    • Generic Algorithms, Binders and Lambda Expressions
  • Chapter 9: Object Optimization
    • Behind the Object
    • Optimizing Objects in Functions
    • Member Functions with Rvalue References
    • Move Semantics and Perfect Forwarding
  • Chapter 10: Smart Pointers
    • Smart Pointers
    • Smart Pointers without Reference Counting
    • Smart Pointers with Reference Counting
    • Custom Deleters
  • Chapter 11: Function Objects and Binders
    • More about Binders
    • Introduction to std::function
    • Template Specialization and Argument Deduction
    • More about std::function
    • std::bind(): A Simple Thread Pool
    • More about Lambda Expressions
  • Chapter 12: Multithreading
    • Important Features in C++11
    • Multithreaded Programming with std::thread
    • Mutual Exclusion
    • Producer-Consumer Problem
    • Atomic Operations
    • Thread Visibility and volatile
  • Chapter 13: Design Patterns
    • Singleton Pattern
    • Factory Pattern
    • Proxy Pattern
    • Decorator Pattern
    • Adapter Pattern
    • Observer Pattern
Powered by GitBook
On this page

Was this helpful?

  1. Chapter 9: Object Optimization

Move Semantics and Perfect Forwarding

In the previous article, we learned member functions with Rvalue references as parameters. Member functions with Rvalue references are widely used in STL containers to improve performance. For example

int main() {
    vector<MyString> v;
    MyString s = "aaa"
    v.push_back(s);
    v.push_back(MyString("bbb"));
    return 0;
}

The first push_back() takes a MyString object, whose normal copy constructor will be called in the container. The latter one takes a temporary object, whose copy constructor with Rvalue reference will be called.

We have written a MyVector in previous chapters. Now let's modify it to add member functions with Rvalue references. We've already have a normal version of push_back as

void push_back(const T &val) {
    if (full()) expand();
    _allocator.construct(_last, val);
    _last++;
}

which calls the construct() method of the allocator. The Rvalue reference version of push_back() can be written as

void push_back(T &&val) {
    if (full()) expand();
    _allocator.construct(_last, val);
    _last++;
}

Inside push_back() we called constrct(), so its Rvalue reference version should be implemented as well.

void construct(T *p, T &&val) { new (p) T(val); }

But the Rvalue reference val is a Lvalue itself, which means that constrct(_last, val) will always call the Lvalue reference version. To fix this, we can use std::move() here, which is called the move semantics.

#include <utility>

std::move() is used to indicate that an object may be "moved from". In specific, it is exactly equivalent to a static_cast to an Rvalue reference type. We can use std::move() to cast val into its Rvalue reference:

void push_back(T &&val) {
    if (full()) expand();
    _allocator.construct(_last, std::move(val));
    _last++;
}

Similarly, std::move() should be used in construct() as well:

void construct(T *p, T &&val) { new (p) T(std::move(val)); }

Now we have the corresponding Lvalue reference and Rvalue reference member functions. But should we defined two functions every time? It seems not a good way of reusing code. A better approach is to use the type deduction of function templates:

template <typename Ty>
void push_back(Ty &&val) {
    if (full()) expand();
    _allocator.construct(_last, std::forward<Ty>(val));
    _last++;
}

In the above code, we defined a template function push_back() which takes a parameter of type Ty &&. When a Lvalue is passed in, val will also be a Lvalue because of the type deduction. Instead, if a Rvalue is passed in, val will be a Rvalue. But how could the corresponding version of construct() be called properly, since val is always treated as a Lvalue? Here we need to use std::forward(), which is known as perfect forwarding.

std::forward() forwards Lvalues as either Lvalues or as Rvalues, depending on the type. Then the corresponding version of construct() can be called.

Similarly, construct() can also be rewritten into template function as

  template <typename Ty>
  void construct(T *p, Ty &&val) {
    new (p) T(std::forward<Ty>(val));
  }

std::forward() is also used here to call the corresponding copy constructor of type T.

PreviousMember Functions with Rvalue ReferencesNextSmart Pointers

Last updated 5 years ago

Was this helpful?