Consider the following code:
struct Temp{ int i = 0; };
Temp GetTemp() { return Temp{}; }
int main()
{
for (struct{Temp const & t; int counter;} v = {GetTemp(), 0};
v.counter < 10;
++v.counter)
{
// Is v.t guaranteed to not be a dangling reference?
std::cout << v.t.i << std::endl;
}
}
So GetTemp()
returns a temporary object, which then gets assigned to a constant reference variable. However, that constant reference variable is a member of an anonymous local struct. Question: Does the C++ standard guarantee that the lifetime of that temporary gets extended till after the loop terminates?
Considering this question, I would have expected the answer to be no, i.e. that I get a dangling reference in the loop body. However, gcc and clang seem to extend the lifetime (see example on godbolt), and even do not complain with -fsanitize=undefined
, which surprised me.
foreach(x,c)
macros, which expand to for loops.x
is the loop variable,c
the container. The macro definition usesc
directly multiple times. The library sometimes calls it likeforeach(x,Get temp())
, meaning theGetTemp
is called multiple times. I looked for ways to store the temporary properly in a local variable. But I can't just doauto&& t=c;
in the macro definition before the for loop, as this would break in e.g.if(...) foreach(...){}
due to missing if-braces. – Vintner