3

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?

1
  • Is it not obvious? Commented Dec 13, 2016 at 21:44

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Better than my answer. Good job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.