how to get value from a register(get a reference with register address)

I had designed the following code to practice my c++ skill
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 #include<iostream>
 using namespace std;

 class classA
 {
         private:
                 int& y;
         public:
                 operator int(){return y;}
                 int& operator()() {return y;}
                 classA(int val):y(val){}
 };

 int main()
 {
         classA classa(8);
         cout<<classa()<<endl;
         cout<<classa<<endl;
 }

If i comment the Num 17 line,the return value is correct,or else it return the register address,so I want to get the value from the register address,but I don't know how to do it.Any ideas to get the value would be appreciated.
Last edited on
On line 11 you are initializing y ( which is a reference ) to a temporary ( the constructor parameter )
This will lead to weird results

Please use [code][/code] tags when posting code in the forum
Your conclude seems well,an reference must be related to a real allocated area.But if I comment line 11 ,the line 18 return the correct result.This hints the operator overload function must done something cause this error,I think the return value of int& operator()() is the real reason,so I test it as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 #include<iostream>
 using namespace std;

 class classA
 {
         private:
                 int& y;
         public:
                 operator int(){return y;}
                 int operator()() {return y;}
                 classA(int val):y(val){}
 };

 int main()
 {
         classA classa(8);
         cout<<classa<<endl;
         cout<<classa<<endl;
 }


the return value shows as follows:
8
34513960

and I can trust that the error result 34513960 is a register address(using gdb detection),the test shows this error is not due to int& operator()(),That is when I notice that I was wrong.The real reason is as you said the constructor parameter is temporary,This is an important lesson to me.The constructor parameter had been free after I called a member function I thought.Thank you Bazzy.
Last edited on
Topic archived. No new replies allowed.