Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::ref using with template function and function passing by value

Tags:

c++

c++11

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?

like image 880
M. S. Avatar asked Jul 22 '26 02:07

M. S.


1 Answers

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.

like image 121
Vittorio Romeo Avatar answered Jul 24 '26 15:07

Vittorio Romeo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!