Reputation: 340
I'm writing a code and I have a question about references&:
class A{
private:
int num;
public:
void set(const int& a){num = a;}
void foo(){
int a = 4;
set(a);
}
void print(){
cout << num << endl;
}
};
int main(){
A a;
a.foo();
a.print();
return 0;
}
In this case, the variable a
will be destroyed at the end of foo()
. set
take the reference, so the address of a
and updates num
. Therefore is this code wrong (num points to a deleted memory)? Or set
, sets num with the value (not the address) of a?
I edit the code with a cout
of address of a
and num
and they are different, so I think that num copies the value of a
. If I run the code, all seems works, but I'm not sure.
Upvotes: 0
Views: 76
Reputation: 11769
Your code isn't invalid, because the code num = a
, takes a copy of a. Plus, set()
is called BEFORE the objects memory is returned, so everyone has a copy, and nothing invalid happens. Also, remember, that num
lasts while the class's instance lasts, so don't worry about deleted memory.
Upvotes: 2