Defensive Copies in Modern C++

La versión moderna de C++ soluciona este problema de forma diferente:

std::string s1 = "Cpp";
std::string s2 = s1;  // Duplicar datos en s1.
  • Los datos de la stack de s1 se duplican y s2 obtiene su propia copia independiente.
  • Cuando s1 y s2 salen del ámbito, cada uno libera su propia memoria.

Antes de la asignación de copias:

StackHeaps1ptrCpplen3capacity3

Después de la asignación de copia:

StackHeaps1ptrCpplen3capacity3s2ptrCpplen3capacity3

Puntos clave:

  • C++ has made a slightly different choice than Rust. Because = copies data, the string data has to be cloned. Otherwise we would get a double-free when either string goes out of scope.

  • C++ also has std::move, which is used to indicate when a value may be moved from. If the example had been s2 = std::move(s1), no heap allocation would take place. After the move, s1 would be in a valid but unspecified state. Unlike Rust, the programmer is allowed to keep using s1.

  • Unlike Rust, = in C++ can run arbitrary code as determined by the type which is being copied or moved.