I have two functions:
void fun(int k) {
++k;
}
template<class T>
void inc(T t) {
++t;
}
And I call these functions with std::ref:
int p = 5;
int o = 5;
fun(std::ref(p));
inc(std::ref(o));
After that value of p is 5 and value of o is 6. What is the difference when I call function with std::ref for these functions?
std::ref returns an std::reference_wrapper, which is implicitly convertible to the type it's wrapping.
When calling fun(std::ref(p)), you're implicitly converting the newly crated std::reference_wrapper to int, making a copy.
When calling inc(std::ref(p)), you're copying the std::reference_wrapper itself, preserving reference semantics.
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