mirror of
https://github.com/google/comprehensive-rust.git
synced 2024-12-14 22:15:54 +02:00
Update double-free-modern-cpp.md (#1192)
From a discussion in #1122 where I realized that the heading is hard to translate. I added a bit of commentary as part of #1083.
This commit is contained in:
parent
354f3afa7c
commit
5bf99115fe
@ -1,4 +1,4 @@
|
||||
# Extra Work in Modern C++
|
||||
# Defensive Copies in Modern C++
|
||||
|
||||
Modern C++ solves this differently:
|
||||
|
||||
@ -49,3 +49,23 @@ After copy-assignment:
|
||||
: : `- - - - - - - - - - - -'
|
||||
`- - - - - - - - - - - - - -'
|
||||
```
|
||||
|
||||
<details>
|
||||
|
||||
Key points:
|
||||
|
||||
- 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.
|
||||
|
||||
[`std::move`]: https://en.cppreference.com/w/cpp/utility/move
|
||||
|
||||
</details>
|
||||
|
Loading…
Reference in New Issue
Block a user