About invalid C ++ references being created or used, what makes the program ill-formed?
See this little piece of code:
std::deque<BIG> bigs {};
// add some BIGs in the deque
BIG& last_BIG { bigs.front() };
f(last_BIG);
bigs.pop_front();
g();
After the call, the pop_front
link is last_BIG
invalid, is it enough to make the program malformed? In other words, should I put last_BIG
in a smaller area?
Of course using last_BIG
undefined after bubbling.
source to share
No, an invalid reference or bad pointer does not by itself invalidate your program. Using it after it's invalidated will definitely be undefined, but creating it is not a problem in itself.
This is similar to creating dangling pointers, except that pointers offer more ways to invalidate them:
int *a = new int;
delete a;
At this point, it a
is an invalid pointer, just like the post pop_front
in your code last_BIG
is an invalid reference. This is fine as long as you are not looking for an invalid pointer or accessing an invalid link.
source to share
In essence, when you use, and you take the memory address of the BIG object. If the memory address is on the heap (made with a new one) then you're fine. On the other hand, if it is a stack reference, then it will technically invalidate after you leave the function you are currently in. Regardless, the object had to be declared and memory had to be allocated for it.
No, that doesn't invalidate last_BIG.
source to share