PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

[FIXED] Why does my std::ref not work as expected?

 July 06, 2022     c++, higher-order-functions, pass-by-reference, pass-by-value, reference     No comments   

Issue

std::ref gives you a lvalue-reference to something. This reference is wrapped into an object that you can then pass around either by reference or by value.

The expected behavior of the code below is that it prints i is 2, but it prints i is 1. Why is that?

Why do I have this expectation? Because I am passing tmp via std::ref to wrapper. In wrapper the reference is then captured by value. I would have assumed that, since I am using std::ref this value is now still a reference to tmp. I am changing tmp and would expect that f reflects that change.

Play with the code here.

#include <iostream>
#include <functional>

template<typename F>
auto wrapper(int i, F func) {
    return [=]() { return func(i); };
}

void f(int i) {
    std::cout << "i is " << i << '\n';
}

int main() {
    int tmp = 1;
    auto func = wrapper(std::ref(tmp), f);
    tmp = 2;
    func();
}

Solution

The reason this does not work is because your wrapper function takes an int as argument.

std::ref returns a std::reference_wrapper. When you pass it to a function that wants an int you will get an implicit conversion and you arre no longer working with a reference.

If you change your function signature to use a std::reference_wrapper it will give the intended result.

#include <iostream>
#include <functional>

template<typename F>
auto wrapper(std::reference_wrapper<int> i, F func) {
    return [=]() { return func(i); };
}

void f(int i) {
    std::cout << "i is " << i << '\n';
}

int main() {
    int tmp = 1;
    auto func = wrapper(std::ref(tmp), f);
    tmp = 2;
    func();
}


Answered By - super
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing