How do I use std::move correctly in C++?

Using std::move correctly in C++ allows you to optimize your code by enabling move semantics. This is particularly useful when dealing with resource management, such as memory allocations, for achieving better performance.

When you use std::move on an object, it indicates that the resources held by that object can be transferred to another object, rather than being copied. This is especially beneficial for classes that manage dynamic resources, such as std::vector or other containers.


#include <iostream>
#include <vector>
#include <utility> // for std::move

class IntVector {
public:
    IntVector(size_t size) : data(new int[size]), size(size) {}
    
    // Move constructor
    IntVector(IntVector&& other) : data(other.data), size(other.size) {
        other.data = nullptr; // Leave 'other' in a valid state
        other.size = 0;
    }
    
    ~IntVector() {
        delete[] data;
    }

private:
    int* data;
    size_t size;
};

int main() {
    IntVector vec1(10);          // Create an IntVector
    IntVector vec2(std::move(vec1)); // Move vec1 into vec2
    return 0;
}
    

C++ std::move move semantics resource management performance optimization