4 ms·
Use-after-move is allowed because of existence of value categories, if you use a return value from a function its creation is usually elided or it is moved, but
by silent_hunter 10y ago
Use-after-move is allowed because of existence of value categories, if you use a return value from a function its creation is usually elided or it is moved, but you can't access that temporary without directly referencing it. When you move an existing object (by specifically saying std::move), what should happen with it? Destroying the object is not a solution because its variable might be still accessible in existing scope (something like dangling a reference in the middle of a scope), which imply use-after-move should be prohibited be language and all variables should have a "not-a-value" state and throw exceptions on use.
- Manishearth 10y ago> When you move an existing object (by specifically saying std::move), what should happen with it? You don't destroy it, you treat it as an actual "move", where the compiler will not consider the original variable as accessible after this point, and not allow accesses after the move. The memory it took up is free for reuse, and no destruction code is run on the side of the code doing the moving (in the case of a conditional move this gets a tiny bit more complex, but not too much). "It's variable will be still accessible in local scope" is exactly what I'm getting at; you can enforce at compile time that this isn't the case by simply disallowing access. You shouldn't have local references active, just like how you shouldn't have local references to the contents of a vector when you push to it. You can already invalidate local references to a part of a struct when something gets moved in modern C++. Being wary of invalidating local references is an established concept in C++; this doesn't exacerbate that problem. It's even better if you track scopes in references which gets rid of the dangling reference problem entirely but at this point you've reinvented Rust :p To be clear, I'm talking of a completely different model that could have been used in place of the rvalue reference and move model. Making C++ have linear types now would be tough, but it could have been done before. There are different tradeoffs there, but I suspect it would have been safer. > all variables should have a "not-a-value" state and throw exceptions on use. You can make this a compile time error. Like I said, linear typing is a pretty well established pattern.