'in C++ can i add a note that a reference variable is no longer valid
I recently had a bug in my code caused by me resizing a vector and I had a variable that was referencing one of its elements. I found the bug, but was wondering if there is a way to tell the compiler/IDE to throw an error if a variable is used after a specific point?
Totally stupid example, but shows what I mean:
vector<int> a{0,1,2,3,4,5,6,7,8,9};
for (auto &value: a) {
int copy=value; //totally stupid but makes sense if vector<int> was actually a vector<some big class> and we are only copying one value
if (value==5) a.resize(a.size()+5);
///value may no longer be valid after this point throw error if try to use value
//can do stuff with copy but not value here
}
Solution 1:[1]
A way to achieve this is to take your file, change the variables that you want to track for future use, for example, if you want to track a variable called foo, rename it to foo_test in all its occurrences prior to the point you are interested about and try compiling/building/testing. If you get an error saying that foo was not defined, then it is used later. If you do not get such an error, you are no longer using it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lajos Arpad |
