4 ms·
But this is purely by convention isn't it? You as the programmer have to know that deque<> never changes item locations in memory under the hood like vector<> d
by flohofwoe 6y ago
But this is purely by convention isn't it? You as the programmer have to know that deque<> never changes item locations in memory under the hood like vector<> does, the compiler will not complain either way.
There's nothing in the interface of vector<> or deque<> that somehow hints to the user or (more importantly) to the compiler that one randomly moves things around in memory and the other doesn't. That's what makes C++ so extremely memory-unsafe (IMHO it's even worse in C++ than C, because at least in C, dynamic memory management usually is right in your face and not hidden under a sugarcoating layer like nearly everywhere in the C++ stdlib).
- millstone 6y agoRight. Iterator invalidation rules are important yet only checked indirectly, through tools like ASAN or VC++ debug iterator support. It's a big problem. But Rust has its conventions too. Probably you would satisfy the borrow checker through an index instead of a pointer: let mut xs = vec![1, 2, 3]; let idx = 0; xs.push(92); println!("{}", xs[idx]); This is memory safe, but in an unsatisfying way. Nothing hints to the compiler that idx is connected to the vector. If you inserted into the front rather than the back, you would have a "dangling index". You just have to know to not do that. It's purely by convention too, except there's no tooling support to help. It turns out programs really do need a way to hold references to collection elements across mutation.
- deleted 6y ago[deleted]
- zbentley 6y ago> This is memory safe, but in an unsatisfying way. How is it unsatisfying? I know that "xs[idx]" isn't going to be garbage data from elsewhere in my program, and that it won't occasionally segfault when I try to print it. That's a big improvement.