[gnu.g++.help] functions and results by reference

mnl@idtsun1.e-technik.th-darmstadt.de (Michael@mitvma.mit.edu N. Lipp) (12/10/90)

Hello,

I have a problem with functions returning their result by reference.
To illustrate my problem, I tried to reduce it to this short (but not
very useful) example:
------------------------------------------------------
#include <stream.h>

class C1
{
  int i;
public:
  C1(int ii) {i = ii; cerr << "C1 created\n";}
  ~C1() {cerr << "C1 deleted\n";}
  friend val (C1& i) { return i.i; }
};

C1 f(int i)
{
  return C1(i);
}

main()
{
  cout << val (f (5)) << '\n';
}
------------------------------------------------------
When run, the program prints:

C1 created
C1 deleted
5

No problem. Then I changed the declaration of `f' to: "C1& f(int i)".
I wanted to avoid the copying of the function result when the function
is used as a parameter (as in the example). I'm not sure wether this
thought is correct, the only use of a reference as function result I
found in my books is in conjunction with an "operator =" declaration.
There, I imagine, the left hand side `argument' of the assignment
is passed by reference as a parameter.

There is no left hand side in my use of the function, so what I expected
was the creation of C1, its use "by reference", i.e. without any copying
and its destruction. However, the modified code results in

C1 created
5

There is no destructor-call. I'm using g++ 1.37.1 on a Sparc running SunOS 4.1
and I have no other compiler for verification. Is this a bug or a feature?
Did I get it all wrong?

[I understand that info-g++ is forwarded to comp.lang.c++. Please reply
to me by mail, as we have no news at our site. By the way, does anybody
know a host that forwards comp.lang.c++ to a mailing list (like there is
one for unix.info)?]

    Thanks Michael

-----------------,------------------------------,------------------------------
Michael N. Lipp  !  Institut fuer Datentechnik  !  Phone: 49-6151-163776
                 !  Merckstr. 25     ,----------'  Fax:   49-6151-164976
                 !  D-6100 Darmstadt ! E-Mail:        xdatmnlx@ddathd21.bitnet
                 !  (Germany)        !   mnl@idtsun1.e-technik.th-darmstadt.de
-----------------'-------------------'-----------------------------------------