Move Semantics

Copy operations are expensive. Move semantics allow to move objects instead of copying them.

  class RGBAImage {
    size_t m_size;
    unique_ptr<uint32_t[]> m_data;

public:
    RGBAImage(const RGBAImage& im)
        : m_size(im.m_size)
        , m_data(make_unique<uint32_t[]>(m_size))
    {
        // copy data: O(m_size)
        std::copy(im.m_data.get(), im.m_data.get() + m_size, m_data.get());
    }
    
    RGBAImage& operator=(const RGBAImage& im) {
        if (&im != this) {
            m_size = im.m_size;
            m_data = move(make_unique<uint32_t[]>(m_size));
            // copy data: O(m_size)
            copy(im.m_data.get(), im.m_data.get() + m_size, m_data.get());
        }
    }
};
  

In the example the image data gets copied. Large object should not be copied if possible. Instead they should be moved or swapped.

Value Categories

identityno identity
cannot be movedl-value
can be movedpr-valuex-value

More details: LValues and RValues Visual CPP

Code Snippet

l-values and r-values can be identified via the following code snippet.

  #include <iostream>
using namespace std;

void print(int& i) {
    cout << "l-value: " << i << endl;
}

void print(int&& i) {
    cout << "r-value: " << i << endl;
}

int main() {
    int i = 42;
    print(i); // l-value
    print(42); // r-value
    print(move(i)); // r-value
}