Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ can a temporary lambda be passed by reference (works on msvc/windows but not gcc/linux)?

Lets say I have the following code snippets:

// global variable
std::thread worker_thread;

// Template function
template <typename Functor>
void start_work(Functor &worker_fn)  // lambda passed by ref
{
    worker_thread = std::thread([&](){
        worker_fn();
    });
}

This is called like this:

void do_work(int value)
{
    printf("Hello from worker\r\n");
}

int main()
{
    // This lambda is a temporary variable...
    start_work([do_work](int value){ do_work(value) });
}

I started developing on MSVC2012. This all compiled up fine and seemed to work. However when I moved onto the gcc compiler on Linux platform I got the following (abbreviated) error:

no known conversion for argument 1 '...__lambda3' to '...__lambda3&'

My Questions:

  • So, from the error I assume that the lambda was a temporary variable and it therefore can't be passed by reference - is that right?
  • Also - any idea why this would work with MSVC? - is it auto-fixing what I wrote?
like image 538
code_fodder Avatar asked Apr 23 '18 12:04

code_fodder


1 Answers

MSVC deviates from the standard in that it allows anonymous temporaries to be bound to non-const lvalue references. You can switch this off using the /Za compiler flag ("disable language extensions"), or the sharper /permissive- option from MSVC2017.

The C++ standard has always been clear that anonymous temporaries can only bind to const references.

like image 118
Bathsheba Avatar answered Oct 17 '22 15:10

Bathsheba