DEV Community

Discussion on: C++ References

Collapse
 
vberlier profile image
Valentin Berlier

I don't write a lot of C++ but shouldn't your code example declare some_value as a reference to int to match the return type of the return_five function?

int &some_value = return_five();
Collapse
 
noah11012 profile image
Noah11012

No, because the non-reference variable will contain the value of the bounded value of the reference.

int value = 100;
int &ref_value = value;
int new_value = ref_value;

std::cout << new_value << "\n"

Output:

100
Collapse
 
vberlier profile image
Valentin Berlier

Oh yeah okay you're dereferencing when assigning to some_value, gotcha. Just another question: if you use auto, what would the inferred type be?

int value = 100;
int &ref_value = value;
auto new_value = ref_value;

Does new_value remain a reference or now contains the dereferenced value?

Thread Thread
 
noah11012 profile image
Noah11012

Not entirely sure as auto in some instances is tricky. I believe in your example that new_value will the type int.

Thread Thread
 
dwd profile image
Dave Cridland

It will be int&, I think: en.cppreference.com/w/cpp/language...