Topic: [Q] Temporary persistence/type conversion
Author: baruch@nynexst.com (Robert Baruch)
Date: 26 May 1994 15:22:09 GMT Raw View
Howdy,
[ Please respond via e-mail, thanks ]
I'm having a problem understanding the persistence of temporaries both
explicit and implicit via type conversion operations.
First, let me tell you what I think the ARM says, and you can correct me
if I'm wrong.
12.2 Temporary Objects says that when a temporary is created, you can either
copy it or bind a reference to it. The moment you copy a temporary, the temporary
may be destroyed, and when you bind a reference to it, the temporary cannot be
destroyed until the reference is destroyed.
So if I do this:
---------------------------------------------------
class X
{
public:
X(int);
X(void);
void member_function(void);
};
void foo(void)
{
X x;
x = X(1); // temporary 1
{
X& ref = X(2); // temporary 2
x = ref;
} // end of scope 2
X(3).member_function(); // temporary 3
} // end of scope 1
---------------------------------------------------
Then temporary 1 can be destroyed immediately after it is copied, and
temporary 2 cannot be destroyed until scope 2 ends. Further, the use of
temporary 3 is not guaranteed to work because it is neither copied nor bound
with a reference. It is temporary 3 that I'm not sure my interpretation is
correct about. And here's why I'm not certain:
12.3.2 Conversion Functions has a little example:
-------------------------------------
class X
{
public:
operator int();
};
class Y
{
public:
operator X();
};
Y a;
int b=a; // illegal: a.operator X().operator int() not tried
int c = X(a); // ok: a.operator X().operator int()
-------------------------------------
That last line is evidence that functions can be called on temporaries, since
a.operator X() is a temporary, and operator int() is the function called on
that temporary. That means that X(a), according to 12.2, either has its value
fetched or is bound by a reference. Which is it, and why?
Now, another question is, if taking the address of a temporary is not binding
a reference to that temporary (i.e. X* x = &X(2); x->member_function(); doesn't
work) then why does this work (or does it?):
-------------------------------------
void foo(const X *x);
foo(&X(7));
-------------------------------------
and if that works, then does that imply that this would also work:
(&X(7))->member_function();
Well, that's all for now. If anyone can clear up the use of temporaries for me,
I'd really appreciate it.
Thanks much,
--Rob