Lifetime temp with temp subexpressions attached to a link

Is it safe to use p

internally main

: I suppose the binding of the timecode generated mk_pair

is extended to the lifetime p

, but what about the temporary objects created with Wrap{1}

and Wrap{2}

?

struct Wrap { int &&x; };

struct Pair { Wrap &&w1, &&w2; };

Pair mk_pair(Wrap &&w1, Wrap &&w2) { return Pair{std::move(w1),std::move(w2)}; }

int main(int argc, char *argv[])
{
  Pair &&p = mk_pair(Wrap{1},Wrap{2});
  std::cout << p.w1.x << ' ' << p.w2.x << '\n';
  return 0;
}

      

+3


source to share


2 answers


Not. Wrap{1}

and are Wrap{2}

not attached to automatic links in main

, so they are destroyed at the end of the line.



Pair

returned from mk_pair

has a lifetime extended to p

, but its links are dangling.

+4


source


This behavior is undefined. IN

mk_pair(Wrap &&w1, Wrap &&w2)

      



you take w1

and w2

as rvalue references, which is good, you are extending the life in the function. Then you return an object that refers to those links. The problem is when the expression ends, the temporary ones you passed by reference are destroyed. This means that you know that references are referring to expired objects and by using them is undefined behavior.

+2


source







All Articles