code_fodder
code_fodder

Reputation: 16321

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:

Upvotes: 5

Views: 184

Answers (1)

Bathsheba
Bathsheba

Reputation: 234655

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.

Upvotes: 7

Related Questions