std::vector<int> x = {1, 2, 3};
process(std::move(x));
x.push_back(4);
// Runtime invalid memory access std::vector<int> x = {1, 2, 3};
process(std::move(x));
x.push_back(4);
// Runtime invalid memory accessI can't think of any case that relying on unspecified state is desirable even if it's valid, though I guess it's better if I change that to x.pop_back(); to be clear.
Please let me know if my understanding is incorrect and thanks for the information!
push_back is absolutely defined. pop_back might be undefined, because pop_back is UB on an empty vector. If you like, call clear, and be assured of an empty, reusable vector. It's not idiomatic, but it's safe.
Howard Hinnant had a Stack Overflow reply a while back going through the possible corner cases of this precise question: https://stackoverflow.com/a/17735913
let x = vec![1, 2, 3];
process(std::mem::replace(&mut x, Vec::new()));
x.push(4);
https://doc.rust-lang.org/std/mem/fn.replace.htmlAlthough, are any C++ compilers able to at least issue a warning in this case? It wouldn’t surprise me if they could.
Not necessarily like the example given, but
Object a {std::move(x)};
x.push_back(4);
could/should segfault.Sometimes the compiler calls that destructor after it has finished the move, if the thing is no longer in scope. That should not be confused with a thing happening in the constructor.