Back to Blog

Understanding Move Semantics in Modern C++

January 15, 2024
8 min read
C++Move SemanticsC++11Performance

. An rvalue reference binds to temporary objects that are about to be destroyed.

std::string createString() {
    return std::string("Hello, World!");
}

std::string str = createString(); // Move constructor called, not copy

Move Constructor and Move Assignment

Classes should define move constructor and move assignment operator to take advantage of move semantics:

class MyClass {
public:
    // Move constructor
    MyClass(MyClass&& other) noexcept
        : data_(std::move(other.data_)) {
        other.data_ = nullptr;
    }
    
    // Move assignment
    MyClass& operator=(MyClass&& other) noexcept {
        if (this != &other) {
            delete data_;
            data_ = std::move(other.data_);
            other.data_ = nullptr;
        }
        return *this;
    }
    
private:
    int* data_;
};

When to Use std::move

Use std::move when you want to explicitly indicate that an object can be moved from. This is useful in function returns and when passing objects to move constructors.

Benefits

  • Eliminates unnecessary copies
  • Improves performance, especially with large objects
  • Enables efficient resource management
  • Works seamlessly with STL containers

Understanding move semantics is crucial for writing efficient C++ code in the modern era.