mardi 28 juillet 2015

How to prevent use of variable after its value has been moved to another variable?

With the introduction of std::move in C++ you can get rid of unnecessary copies. Problem is that although you can move the value out of a variable, you cannot prevent the rest of the function to still refer to that variable.

For example, suppose I call a function that returns a big vector, and then (after some more code) I want to move this vector into another variable, like this:

auto lotsOfBooks = getAllBooks();
if (lotsOfBooks.empty())
   return;
...
auto library = Library("National Library", std::move(lotsOfBooks));

After the move of the books container to the library, I don't want the rest of the code to refer to the lotsOfBooks variable anymore. But I don't see a way to prevent this.

I know that in many cases you can simply put part of the function in its own nested block (putting them in curly braces), but this is not always possible. In this case, the problem could be circumvented by using std::unique_ptr<Library> instead of Library, but memory allocations are not always wanted.

Is there a way to prevent usage of a variable after a specific statement/line (either using a compiler construction, a C++ construction, code-checking tool (like Lint), ...)?

Aucun commentaire:

Enregistrer un commentaire