☕ Buy Me Coffee
← Back to Feed

Move Semantics & Rvalue References

Move semantics (C++11) solve the problem of unnecessary deep copies of temporary objects (rvalues). By "stealing" resources like heap-allocated buffers, we achieve constant time "copying".

Rvalue References (&&)

While an lvalue reference (T&) binds to an object with a name, an rvalue reference (T&&) binds to a temporary object that is about to expire.

void process(std::string& lval) { /* copy */ }
void process(std::string&& rval) { /* move */ }

std::string s = "hello";
process(s);            // Calls lvalue version
process("world");      // Calls rvalue version
process(std::move(s)); // Calls rvalue version, s is moved-from

The Rule of Five

To support move semantics, your class should implement:

  1. Destructor
  2. Copy Constructor
  3. Copy Assignment
  4. Move Constructor
  5. Move Assignment

std::forward (Perfect Forwarding)

Used in value-neutral generic code (templates) to forward arguments to another function while preserving their lvalue/rvalue-ness.

// FEEDBACK_LOOP.exe

0.0 / 5.0
FROM 0 PEERS
→ Login to rate