What will the following program output?
#include <iostream>
using namespace std;

struct D {
  D() { cout << "1"; }
  ~D() { cout << "2"; }

D GetResult() { return D(); }

int main() {
  const D &d = GetResult();
  cout << "3";
12.2 Temporary objects
5 ... The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits. A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call. A temporary bound to the returned value in a function return statement (6.6.3) persists until the function exits. In all these cases, the temporaries created during the evaluation of the expression initializing the reference, except the temporary to which the reference is bound, are destroyed at the end of the full-expression in which they are created and in the reverse order of the completion of their construction.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Sign Up Now
or Subscribe for future quizzes