Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up

Explain move semantics, rvalue references and std::move.

Before C++11, returning a large object or inserting into a container meant copying. Move semantics lets you transfer ownership of internal resources instead.

An lvalue has an identity you can take the address of; an rvalue is a temporary about to expire. An rvalue reference, written T&&, binds to those temporaries and says "this object is about to die, so you may steal from it".

class Buffer {
    char* data_; size_t size_;
public:
    Buffer(Buffer&& other) noexcept
        : data_(other.data_), size_(other.size_) {
        other.data_ = nullptr;   // leave source valid and destructible
        other.size_ = 0;
    }
};

A move constructor copies the pointer rather than the megabytes it points at — O(1) instead of O(n).

std::move does not move anything. It is a cast to an rvalue reference, telling the compiler it may select the move overload. After moving from an object, it is in a valid but unspecified state: you may destroy it or assign to it, but not rely on its contents.

Note: Mark move operations noexcept. std::vector will only use a move constructor during reallocation if it is noexcept — otherwise it copies to preserve the strong exception guarantee, and you silently lose the benefit.

All C++ interview questions

Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up as