Skip to content
C++

Move Semantics

Rvalue references and move constructors.

By EZ4Code Team
movemove-semantics

Code

#include <iostream>
#include <string>
#include <vector>
#include <utility>

class StringHolder {
    std::string data;
public:
    // Construct
    StringHolder(const std::string& s) : data(s) {
        std::cout << "copy construct\n";
    }
    // Move constructor
    StringHolder(std::string&& s) : data(std::move(s)) {
        std::cout << "move construct\n";
    }
    // Move assignment
    StringHolder& operator=(StringHolder&& other) noexcept {
        data = std::move(other.data);
        return *this;
    }
    const std::string& get() const { return data; }
};

int main() {
    std::string big = "a very long string...";

    // Move avoids copy
    StringHolder h1(std::move(big));
    StringHolder h2 = std::move(h1);

    // std::move only casts, doesn't actually move
    std::vector<std::string> v;
    std::string s = "hello";
    v.push_back(std::move(s)); // Move into vector

    // Perfect forwarding
    auto wrapper = [](auto&& f, auto&&... args) {
        return f(std::forward<decltype(args)>(args)...);
    };
    return 0;
}

Explanation

Move semantics avoids unnecessary copies via rvalue references; std::move casts to rvalue; std::forward perfectly forwards.

More C++ Snippets