by vaylian · 2y ago · 0 comments
const std::string str { "12345678901234" };
int value = 0;
std::from_chars(str.data(),str.data() + str.size(), value);
On the third line: Why can I just pass in `value` like this? Shouldn't I use `&value` to pass in the output variable as a reference?A non-const reference is just as clear a signal that the parameter may be modified as a non-const pointer. If there's no modification const ref should be used.
You could choose to textually "tag" passing by mutable ref by passing `&foo` but this can rub people the wrong way, just like chaining pointer outvars with `&out_foo`.
So you can dip value into the function call and the function can assign to it, as it could to data pointed to by a pointer.
int x = 0;
int &r = x;
r += 1;
assert(x == 1);
int y;
r = y; // won't compile
void inc(int &r) { r += 1; }
int x = 0;
inc(x);
assert(x == 1);
The equivalent using pointers, like in C: int x = 0;
int *p = &x;
*p += 1;
assert(x == 1);
int y;
p = &y;
void inc(int *p) { *p += 1; }
int x = 0;
inc(&x);
assert(x == 1); r = y; // won't compile
This will compile. It will be effectively the same as "x = y". The pointer equivalent is *p = y".My apologies, as it's been a while since I've used C++.