On Fri, 19 Aug 2005 15:16:31 +0200, Steffen <s.weinstock@gmx.de>
wrote:
[color=blue]
>Hi,
>
>I have a somewhat related question:
>is it defined what happens to a reference after the object it references
>is destroyed? It looks like there would be some sort of copy:
>
>
>#include <iostream>
>using namespace std;
>
>class T {
>public:
> T(int i) {n=i;};
> int n;
> void speak(void) {cout << "Hello " << n << endl;};
>};
>
>class S{
>public:
> S(void) {};
> void shout(void) {cout << "HEEYY!" << endl;};
>};
>
>int main(void)
>{
> T *t_ptr = new T(7);
> T &t_ref = *t_ptr;
>
> cout << "t_ptr: " << t_ptr << '\n'
> << "&t_ref: " << &t_ref << '\n';
>
> t_ref.speak();
>
> delete t_ptr;
>
> t_ref.speak();
>
> S *s_ptr = new S;
>
> cout << "s_ptr: " << s_ptr << '\n'
> << "&t_ref: " << &t_ref << endl;
>
> s_ptr->shout();
> t_ref.speak();
>
> delete s_ptr;
> return 0;
>}
>
>
>produces:
>
>t_ptr: 0x8049f40
>&t_ref: 0x8049f40
>Hello 7
>Hello 0
>s_ptr: 0x8049f40
>&t_ref: 0x8049f40
>HEEYY!
>Hello 0
>
>
>But why is the address the same?
>
>Steffen[/color]
It's undefined behavior. Section 8.3.2, paragraph 4 of the C++
standard says so.
If it works at all one time by pure luck, it might not work the next,
and most certainly will not work all the time on some operating
systems and/or compilers.
--
Bob Hairgrove
NoSpamPlease@Home.com