⚙️ C++ Intermediate

What is move semantics in C++?

Why Interviewers Ask This

This tests whether you can apply C++ knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

Answer

Move semantics (C++11) allow transferring resources from a temporary (rvalue) object to another object instead of copying — dramatically improving performance when dealing with expensive-to-copy objects like vectors, strings, and unique_ptrs. The problem before C++11: returning a vector from a function caused a full deep copy: std::vector<int> makeData() { std::vector<int> v(1000000); /* ... */ return v; // Copy of 1M ints before C++11 }. Rvalue references (&&): bind to temporaries (rvalues — things you can't take the address of): void process(std::vector<int>&& v) { /* v is moved-from */ }. Move constructor and move assignment: class Buffer { char* data; size_t size; public: // Move constructor: Buffer(Buffer&& other) noexcept : data(other.data), size(other.size) { other.data = nullptr; // Leave other in valid but empty state other.size = 0; } // Move assignment: Buffer& operator=(Buffer&& other) noexcept { if (this != &other) { delete[] data; // Release own resources data = other.data; size = other.size; other.data = nullptr; other.size = 0; } return *this; } };. std::move: casts an lvalue to rvalue reference — enabling move: std::vector<int> v1(1000000); std::vector<int> v2 = std::move(v1); // Moves data, v1 is now empty std::cout << v2.size(); // 1000000 std::cout << v1.size(); // 0. Perfect forwarding: template<typename T> void wrapper(T&& arg) { target(std::forward<T>(arg)); // Preserves lvalue/rvalue-ness }. RVO/NRVO: compiler often elides copies entirely (Return Value Optimization) — move semantics are the fallback when RVO can't apply.

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.