C++ is backward compatible with C so it inherited pointers. A quick recap if you don't know what a pointer is: a pointer is a variable that holds t...
For further actions, you may consider blocking this person and/or reporting abuse
I don't write a lot of C++ but shouldn't your code example declare
some_value
as a reference toint
to match the return type of thereturn_five
function?No, because the non-reference variable will contain the value of the bounded value of the reference.
Output:
Oh yeah okay you're dereferencing when assigning to
some_value
, gotcha. Just another question: if you useauto
, what would the inferred type be?Does
new_value
remain a reference or now contains the dereferenced value?Not entirely sure as
auto
in some instances is tricky. I believe in your example thatnew_value
will the typeint
.It will be int&, I think: en.cppreference.com/w/cpp/language...
A reference is, of course, a bit of syntactic sugar for a pointer. But there are two differences:
The last line prints two, because the reference is bound to
one
, and you've just changed the value. The pointer, now also bound to one, therefore prints the same value.You can make a pointer non-rebindable with a
const
after the point, though. References, and const-pointers, are similar to the effect of theconst
keyword in Javascript, and thefinal
keyword in Java.Calling any of these functions with s1 is fine - there's always something to reference. f2() might change the string though.
But you cannot call f2 with either an expression, or a literal - because f2 says it might change the string, f2 cannot be called with a temporary.
No such protections exist for pointers.
You can, though, create a nullptr reference quite easily:
Of course, the moment you do anything with ref, you're implicitly referencing it, and you'll experience the joy of undefined behaviour.