Topic: Temporary objects and ref (&) function arguments


Author: "Rune Jorgensen" <rj@dds.no>
Date: 1997/05/06
Raw View
This is compiled with a MS C++ compiler with the ANSI C(++) (/Za) option
enabled.
It produces the compiler error shown in the source.
I wonder why ANSI C++ cannot accept a reference to a temporary object
(the return value from iFunc()) unless the reference argument is const?
After all, the temporary object is alive till the call to vFunc2 is
finished?
What is the danger of modifying the temporary object in vFunc2?

-Rune Jorgensen
 rj@dds.no

----cut----

#include <stdio.h>
#include <stdlib.h>

int iFunc(
)
{
  return 5;
}

void vFunc2(
  int &ri
)
{
  int i = ri;
  printf("vFunc2(%d)\n", i);
}

int main(
  int iNArg,
  char **asArg
)
{
  int
    i,
    &ri = i;

  vFunc2(i = iFunc());
  vFunc2(ri = iFunc());
  vFunc2(iFunc()); /* tmp.cpp(29) : error C2607: 'initializing' : */
                   /* cannot implicitly convert a 'int ' to a 'int &' */
                   /* that is not const */

  return 0;
}

----cut----
%
---
[ comp.std.c++ is moderated.  To submit articles: Try just posting with your
                newsreader.  If that fails, use mailto:std-c++@ncar.ucar.edu
  comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
  Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
  Comments? mailto:std-c++-request@ncar.ucar.edu
]