Z
ziman137
Hi all,
The results from following codes got me a bit confused.
#include <stdio.h>
#include <iostream>
using namespace std;
struct A {
A () { cout << "A() ctor!" << endl; };
~A() { cout << "~A() dtor!" << endl; };
void foo () { printf("this=%p\n", this); };
int x, y;
};
main ()
{
A& a = a;
cout << "&a=" << &a << endl;
a.foo(); // is it legal here?
// a.x = 10; // illegal here
// a.y = 20;
A a1;
A& a2 = a1;
cout << "&a1=" << &a1 << endl;
cout << "a2."; a2.foo();
}
gcc version 3.2.2 20030222 (Red Hat Linux 3.2.2-5)
this=0x80488ce
A() ctor!
&a1=0xbffff0d0
a2.this=0xbffff0d0
~A() dtor!
What does the initialization of a reference object do? Suppose the
initialization of reference is simply has its "this" pointer to the
target object. This does not call constructor, which is true. For
self-referenced "A& a = a", how can its "this" pointer be correctly
bound to member function foo()? As seen, "a.foo()" works OK! Isn't it
supposed to be illegal?
Any help would be appreciated.
Gary
The results from following codes got me a bit confused.
#include <stdio.h>
#include <iostream>
using namespace std;
struct A {
A () { cout << "A() ctor!" << endl; };
~A() { cout << "~A() dtor!" << endl; };
void foo () { printf("this=%p\n", this); };
int x, y;
};
main ()
{
A& a = a;
cout << "&a=" << &a << endl;
a.foo(); // is it legal here?
// a.x = 10; // illegal here
// a.y = 20;
A a1;
A& a2 = a1;
cout << "&a1=" << &a1 << endl;
cout << "a2."; a2.foo();
}
gcc version 3.2.2 20030222 (Red Hat Linux 3.2.2-5)
&a=0x80488ceg++ -o foo foo.cpp
foo
this=0x80488ce
A() ctor!
&a1=0xbffff0d0
a2.this=0xbffff0d0
~A() dtor!
What does the initialization of a reference object do? Suppose the
initialization of reference is simply has its "this" pointer to the
target object. This does not call constructor, which is true. For
self-referenced "A& a = a", how can its "this" pointer be correctly
bound to member function foo()? As seen, "a.foo()" works OK! Isn't it
supposed to be illegal?
Any help would be appreciated.
Gary