Sobes.tech
Middle

What happens when moving an object of type std::string in C++?

sobes.tech AI

Answer from AI

When moving a std::string, ownership of the resource (memory) is transferred from the source object to the target. Instead of copying the string's contents (characters), only the pointer to the buffer, its size, and capacity are copied. The original object is then put into a valid but unspecified state (usually, the pointer becomes null, and size and capacity are reset), which prevents double freeing of memory. This is significantly faster than copying the entire string, especially for long strings.

#include <string>
#include <iostream>
#include <utility>

int main() {
    std::string original = "A very long string that you don't want to copy";
    std::cout << "Original (before move): " << original << std::endl;

    // Move original into moved
    std::string moved = std::move(original);

    std::cout << "Moved (after move): " << moved << std::endl;
    // original is now in a valid but unspecified state.
    // Using original after move without reinitialization is undefined behavior.
    // However, many implementations reset it to an empty state.
    // std::cout << "Original (after move): " << original << std::endl; // Dangerous!

    return 0;
}

The move constructor or move assignment operator:

  • Assigns the pointer to the buffer to the target object.
  • Assigns the size and capacity to the target object.
  • Sets the buffer pointer of the source object to nullptr.
  • Sets the size and capacity of the source object to 0.

This is implemented thanks to move semantics (rvalue references and special constructors/operators).