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 ys2
obtiene su propia copia independiente. - Cuando
s1
ys2
salen del ámbito, cada uno libera su propia memoria.
Antes de la asignación de copias:
Después de la asignación de copia:
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 beens2 = 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 usings1
. -
Unlike Rust,
=
in C++ can run arbitrary code as determined by the type which is being copied or moved.