c + +可以通过引用传递临时的lambda(在msvc/windows上有效,但在gcc/linux上无效)吗? [英] 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();
});
}
这样称呼:
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) });
}
我开始在MSVC2012上进行开发.所有这些都整理得很好,并且似乎可以正常工作.但是,当我转移到Linux平台上的gcc编译器时,出现以下(缩写)错误:
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&'
我的问题:
- 因此,从错误中我认为lambda是一个临时变量,因此不能通过引用传递-是吗?
- 也-您知道为什么它可以与MSVC一起使用吗? -可以自动修复我写的内容吗?
推荐答案
MSVC不同于标准,它允许匿名临时对象绑定到非常量左值引用.您可以使用/Za
编译器标志(禁用语言扩展")或MSVC2017中更清晰的/permissive-
选项将其关闭.
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.
C ++标准一直很明确,匿名临时对象只能绑定到const
引用.
The C++ standard has always been clear that anonymous temporaries can only bind to const
references.
这篇关于c + +可以通过引用传递临时的lambda(在msvc/windows上有效,但在gcc/linux上无效)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!