How to prevent a variable from being used after its value has been transferred to another variable?

With the introduction of std :: move in C ++, you can get rid of unnecessary copies. The problem is that while you can move a value out of a variable, you cannot prevent the rest of the function from still referencing that variable.

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

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

      

After moving the book container to the library, I no longer want the rest of the code to reference the variable lotsOfBooks

. But I see no way to prevent this.

I know that in many cases you can just put part of the function in your own nested block (by placing them in curly braces), but this is not always possible. In this case, the problem can be worked around by using std::unique_ptr<Library>

instead Library

, but memory allocations are not always required.

Is there a way to prevent a variable from being used after a specific statement / line (either by compiler build, C ++ build, code checker (like Lint), ...)?

+3


source to share


2 answers


You can never stop a programmer from writing a wrong sentence somewhere in your code. What you can (with a compiler):

  • try to find the most common mistakes
  • do your best to catch such errors as soon as possible at runtime (at least when debugging non-optimized mode).


This is what happens to traversal in C ++ 11. The original pointer is null, or the original container is empty. This gives 2 nice results:

  • The destructor cannot break anything (deleting by a null pointer is harmless, so destroying an empty container)
  • any access to the old variable should immediately throw an exception: null access pointer / assignment, out of range index for the vector, etc.
+1


source


As you suggested yourself, you can limit the scope of a variable by placing it in a local block. There is no other way to prevent access to the moved variable.



+1


source







All Articles