beshers@brcsun2.brc.uconn.edu (George Beshers) (05/02/89)
Consider nested functions calls where the first function calls
the second function from the return statement (I think this just
happens in the return statement). The nested function returns
a *reference* to an object which is passed back by *value*.
The constructor is not called and the value is deleted.
For example:
#include <stream.h>
#include <string.h>
struct Ref {
int ref;
char *p;
};
struct Str {
Ref *r;
Str();
Str(char *);
Str(Str &);
~Str();
friend ostream&
operator<<(ostream&, Str);
};
Str::Str()
{ r = 0; }
Str::Str(char *q)
{
r = new Ref;
r->ref = 1;
r->p = new char[strlen(q)];
strcpy(r->p, q);
}
Str::Str(Str &S)
{
r = S.r;
r->ref++;
}
Str::~Str()
{
if (r != 0) {
r->ref--;
if (r->ref == 0) {
delete r->p;
delete r;
}
r = 0;
}
}
ostream& operator<<(ostream& out, Str S)
{
out << S.r->p;
return out;
}
Str A;
Str & f1()
{
return A;
}
Str f2()
{
return f1();
}
main()
{
A = "Test\n";
cout << f2();
cout << A.r->ref << "\n";
}
Sun3/50 nfp
SunOS 3.5
C++ version 1.34.1 with most posted bug fixes.
George Beshers