C++ lambda是如何移动的?
我不明白lambda是怎么移动的。考虑下面的代码:C++ lambda是如何移动的?,c++,c++11,lambda,c++14,move-semantics,C++,C++11,Lambda,C++14,Move Semantics,我不明白lambda是怎么移动的。考虑下面的代码: #include <iostream> #include <utility> #include <string> struct Foo // non-copyable type { Foo() = default; Foo(const Foo&) = delete; // cannot copy Foo(Foo&&) = default; // can mov
#include <iostream>
#include <utility>
#include <string>
struct Foo // non-copyable type
{
Foo() = default;
Foo(const Foo&) = delete; // cannot copy
Foo(Foo&&) = default; // can move
};
auto lambda = [p = Foo()](){
std::string x{"lambda"};
std::cout << x << std::endl;
};
// auto copied_lambda = lambda; // cannot copy due to Foo non-copyable init capture
auto moved_lambda = std::move(lambda); // we moved it
struct Functor // "simulate" a lambda
{
std::string x{"functor"};
void operator()() const
{
std::cout << x << std::endl;
}
};
Functor functor; // initial functor object
auto moved_functor = std::move(functor); // moved it
int main()
{
lambda(); // why does it display "lambda" since it was moved?
moved_lambda(); // displays "lambda", was moved in, everything OK
functor(); // doesn't display "functor", was moved
moved_functor(); // displays "functor", was moved in, everything OK
}
#包括
#包括
#包括
结构Foo//不可复制类型
{
Foo()=默认值;
Foo(const Foo&)=delete;//无法复制
Foo(Foo&&)=默认值;//可以移动
};
自动lambda=[p=Foo()](){
std::字符串x{“lambda”};
std::cout你的函子
与你的lambda不一致。你的lambda实际上看起来像:
struct Functor // "simulate" a lambda
{
void operator()() const
{
std::string x{"functor"};
std::cout << x << std::endl;
}
};
struct Functor//“模拟”lambda
{
void运算符()()常量
{
字符串x{“函子”};
std::cout您的示例不完全相同。lambda的正确模拟应该是:
struct Functor // "simulate" a lambda
{
void operator()() const
{
std::string x{"functor"};
std::cout << x << std::endl;
}
};
struct Functor//“模拟”lambda
{
void运算符()()常量
{
字符串x{“函子”};
std::cout ohhh愚蠢的错误,当然,我现在看到了。两个答案都一样好,我接受你的答案,因为它早了1秒:)要让lamba和函子做同样的事情,你可以在捕获中设置x:[x=std::string{“lambda”}{…}
。还要注意,移动后std::string
中的内容是未定义的,因此即使lambda和functor都会这样做,您得到的也可能是有效的。@haccks认为您的答案更好。尽管有趣的是,如果您将lambda更改为std::string xx{“lambda”};自动lambda=[p=Foo(),xx](){std::cout@Claudiu在非易变的
lambda中,如何用xx+=“x”
编译它?在GCC4.9.2和Clang3.5.0上,从lambda移动的代码对我来说都不会打印任何东西。@Barry:xx
is(也是)一个全局…当移动main中的所有内容时,您在修改xx
时出错。该示例无效-xx
没有自动存储,因此捕获无效(“由简单捕获指定的实体被称为显式捕获,并且应为该实体或在本地lambda表达式的到达范围内声明了自动存储持续时间的变量。”).gcc对此发出警告,并可能最终无法捕获-因此从静止状态移动的文件会打印,因为xx
不是lambda的成员。@Claudiu clang不会编译它(“错误:xx
无法捕获,因为它没有自动存储持续时间”)