Topic: Passing this pointer of temporary object
Author: "Ed Brey" <brey@afd.mke.etn.com>
Date: 1999/03/13 Raw View
Is it legal to pass a this pointer returned from a temporary object to a
function? Here's an example:
#include <iostream>
struct A {
A() {i = 123456;}
const A* Ptr() {return this;}
int i;
};
void fn(const A* a) {
std::cout << a->i << std::endl;
}
int main() {
fn(A().Ptr());
return 0;
}
I expected that the temporary object of class A would have been overwritten
on the stack by the parameters to fn. However, upon trying it, I found that
this code worked when compiling under egcs-2.91.57 and Microsoft Visual C++
6 SP2 targeting Win32.
Is this legal C++? Or did I just get "lucky" that it worked?
(The reason I'm doing this is that I am writing some glue between two fixed
interfaces that take pointers to different structures, say Source and Dest.
My function gets passed a Source pointer and must call a function passing
Dest pointer. There are many calls that do this, so I wanted to write a
class to inherit from Dest that would be equivalent to A above, but take a
Source* in its constructor.)
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]
Author: Bruce Visscher <bvisscher@mindspring.com>
Date: 1999/03/13 Raw View
Ed Brey wrote:
> Is it legal to pass a this pointer returned from a temporary object to a
> function? Here's an example:
>
> #include <iostream>
>
> struct A {
> A() {i = 123456;}
> const A* Ptr() {return this;}
> int i;
> };
>
> void fn(const A* a) {
> std::cout << a->i << std::endl;
> }
>
> int main() {
> fn(A().Ptr());
> return 0;
> }
The temporary is not destroyed until the end of the expression, so IMHO, this
should be legal.
Bruce Visscher
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]