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

Friday, November 4, 2022

[FIXED] Why does passing functions by value work but not by reference

 November 04, 2022     c++, function, lambda, pass-by-reference, temporary-objects     No comments   

Issue

Here I have the code

void foo(std::function<int(int)> stuff){
   //whatever
}

and it is called with

auto fct = [](int x){return 0;};

foo(fct);

Which works great. However, when I change foo to

void foo(std::function<int(int)>& stuff){ // only change is that it is passed by reference
   //whatever
}

The code doesn't compile. Why is this the case? I know we can just pass the object to a reference parameter directly, we don't need the & operator like for pointers. Why can't you pass std::function types by reference?


Solution

You are trying to bind a non-constant reference with a temporary object.

You could use a constant reference.

Here is a demonstration program.

#include <iostream>
#include <functional>

void foo( const std::function<int(int)> &stuff )
{
   int x = 10;

   std::cout << stuff( x ) << '\n';
}

int main()
{
    auto fct = [](int x){return x * 10;};

    foo(fct);
}

The program output is

100

Without the qualifier const you could write for example

#include <iostream>
#include <functional>

void foo( std::function<int(int)> &stuff )
{
   int x = 10;

   std::cout << stuff( x ) << '\n';
}

int main()
{
    auto fct = [](int x){return x * 10;};

    std::function<int(int)> f( fct );

    foo(f);
}

As for the lambda-expression then according to the C++ 17 Standard (8.1.5.1 Closure types)

1 The type of a lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type, called the closure type, whose properties are described below.



Answered By - Vlad from Moscow
Answer Checked By - Candace Johnson (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