I've seen other posts on this but didn't really get what happens yet.
so say i have this code:
template<typename T>struct S {
S(T value):val{value}{}
T& get(){return val;}
private:
T val;
};
int main(){
S<int>s1{5};
int n = s1.get();
n = 10;
std::cout<<s1.get();
}
this prints: 5
my question is why if i returned a reference to val doesn't the value of val change when i changed the value of n?
When you store the result in int n
you create a copy. Try:
int &n = s1.get();
If you do
int& n = s1.get();
n = 10;
std::cout << s1.get();
You will see 10.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With