Thread View: gnu.g++.help
1 messages
1 total messages
Started by Michael N. Lipp
Mon, 10 Dec 1990 14:11
functions and results by reference
Author: Michael N. Lipp
Date: Mon, 10 Dec 1990 14:11
Date: Mon, 10 Dec 1990 14:11
65 lines
2751 bytes
2751 bytes
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
-----------------'-------------------'-----------------------------------------
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads