Jump to content

Move semantics

From Wikipedia, the free encyclopedia

Move semantics are a feature in some programming languages, especially those which enforce strict ownership. Although the feature was first popularised in C++11 with the introduction of rvalue references and the standard library std::move() move function, the feature exists in many languages such as C++, Rust, D, Swift.

C++

[edit]

C++ first introduced move semantics in C++11. The primary motivation behind move semantics was to provide the ability to move an expensive object from one address in memory to another without having to rely on copies, which can be expensive.[1] C++11 introduced rvalue references and the functions std::move() and std::forward() to the C++ Standard Library. It further expands the "rule of three" to the "rule of five" with move constructors and move assignment operators.[2]

Rvalues

[edit]

An rvalue reference (the 'r' can be seen as meaning "read" and also because they appear on the right-hand side of an assignment, while 'l' in "lvalue" can be seen as meaning "locator" and because they appear on the left-hand side) typically represents a temporary value, literal, or a result of an expression without a persistent name or memory address that can be relied on. In the language, an lvalue reference is denoted with a single ampersand (for example int&), while an rvalue reference is denoted with a double ampersand (for example int&&). Because the bound object is temporary or expiring, an rvalue reference essentially indicates that it is s safe to move it rather than copy it.

Move constructors

[edit]

A move constructor is a constructor that can be called with an argument of the same class type and copies the content of the argument, possibly modifying the argument.[3]

The move constructor has the following signature, inside a class X:

class X {
private:
    // ...
public:
    // Move constructor:
    X(X&& other) noexcept;
};

A type can be made move-only by disabling the copy constructor with = delete.

Move assignment operators

[edit]

A move assignment operator is a non-generic non-static assignment operator (operator=) that can be called with an argument of the same class type and copies the content of the argument, possibly modifying the argument.[4]

The move constructor has the following signature, inside a class X:

class X {
private:
    // ...
public:
    // Move assignment operator:
    X& operator=(X&& other) noexcept;
};

Move functions

[edit]

std::move() is a function in the standard library that indicates that the object passed to it may be "moved from"; it in specific creates an xvalue expression that identifies its argument of type T. This is equivalent to a cast to std::remove_reference_t<T>&&.[5] In addition, the std::move_if_noexcept() function can be used to convert the argument to an xvalue, if its move constructor cannot throw an exception.[6]

std::forward() is another function in the standard library, especially used in template code, for "perfect forwarding". Perfect forwarding means preserving whether a function argument was originally an lvalue or an rvalue when passed into another function. std::forward() works by performing a cast of its argument of type T to T&&.[7] std::forward_like(), introduced in C++23, [8] forwards its argument with the same value category and const-ness of the type, ensuring that the parameter behaves like an expression of the function's type parameter T.

All of these functions appear in the <utility> header.[9]

Smart pointers

[edit]

The unique pointer type std::unique_ptr<T> relies directly on move semantics to enforce exclusive ownership of a dynamically allocated resource while allowing the ownership to be transferred safely across scopes and objects.[10]

Rust

[edit]

Rust uses move semantics differently from C++. While C++'s assignment operation creates a copy of an object, in Rust, the same assignment transfers ownership.[11]

For example, in C++:

using std::string;

string s1 = "Hello";
string s2 = s1; // s2 is made by a copy of s1
std::println("s1 = {}", s1); // "s1 = Hello"
std::println("s2 = {}", s2); // "s2 = Hello"

In Rust:

let s1 = String::from("Hello");
let s2 = s1; // ownership transfers to s2 from s1
// println!("{s1}"); // Compile-time error, borrow of moved value s1
println!("{s2}"); // "s2 = Hello" ; s2 is the sole owner

Rust additionally has a move keyword, but this is used specifically for closures. The keyword forces the closure to take ownership of the variables it captures from its environment, rather than borrowing them by reference.[12]

let data = vec![1, 2, 3];
let closure = move || println!("Captured {data:?} by value");
// println!("data: {data:?}"); // data no longer available (owned by closure)

This is particularly used when spawning threads.

use std::thread;

let data = vec![1, 2, 3];

thread::spawn(move || {
    println!("Captured {data:?} by value");
}).join().unwrap();

Rust's unique pointer type, std::boxed::Box<T>, however, does not implement the std::marker::Copy trait, because it manages heap resources or reference counts.[13] To clone, it must use the clone() method.

Other languages

[edit]

Swift has a consume keyword since Swift 5.9, which behaves the same as C++'s std::move() operator. It forces a value to be moved rather than copied, and immediately ends the lifetime of the original binding. By default, Swift automatically optimises away unnecessary copies and Automatic Reference Counting retain/release calls. A move-only type can be created by marking the type with the protocol ~Copyable (which suppresses the Copyable protocol). Swift can additionally annotate parameters with borrowing (for temporary read-only access), inout (for temporary borrowing), and consuming (for permanent ownership transfer).

D assumes by default that all structs are bitwise-movable (relocatable via memcpy), unlike C++ which disallows moving unless a move constructor exists. D's equivalent to C++'s std::move() is std.algorithm.mutation.move().[14] Note that D distinguishes between class and struct; classes are reference types (similar to Java and C#), but structs are value types and therefore are subject to move semantics. A type can be made move-only by marking the copy constructor @disable (like @disable this(this)), this makes the type only movable via move() or ref.

References

[edit]
  1. ↑ Howard E. Hinnant; Peter Dimov; Dave Abrahams (10 September 2002). "A Proposal to Add Move Semantics Support to the C++ Language". open-std.org. WG21.
  2. ↑ Microsoft Learn (3 August 2021). "Move Constructors and Move Assignment Operators (C++)". learn.microsoft.com. Microsoft Learn.
  3. ↑ cppreference.com. "Move constructors". cppreference.com. cppreference.com. Retrieved 28 November 2026.
  4. ↑ cppreference.com. "Move assignment operator". cppreference.com. cppreference.com. Retrieved 28 November 2026.
  5. ↑ cppreference.com. "std::move". cppreference.com. cppreference.com. Retrieved 28 November 2026.
  6. ↑ cppreference.com. "std::move_if_noexcept". cppreference.com. cppreference.com. Retrieved 28 November 2026.
  7. ↑ cppreference.com. "std::forward". cppreference.com. cppreference.com. Retrieved 28 November 2026.
  8. ↑ cppreference.com. "std::forward_like". cppreference.com. cppreference.com. Retrieved 28 November 2026.
  9. ↑ cppreference.com. "Standard library header <utility>". cppreference.com. cppreference.com. Retrieved 28 November 2026.
  10. ↑ cppreference.com. "std::unique_ptr". cppreference.com. cppreference.com. Retrieved 28 November 2026.
  11. ↑ The Rust Team (29 September 2026). "Ownership and moves". doc.rust-lang.org. Rust By Example.
  12. ↑ The Rust Team (25 November 2026). "Keyword move". doc.rust-lang.org. The Rust Team.
  13. ↑ The Rust Team (25 November 2026). "Struct Box". doc.rust-lang.org. The Rust Team.
  14. ↑ Andrei Alexandrescu. "Function std.algorithm.mutation.move". dlang.org. D Language Foundation. Retrieved 28 November 2026.