当我[=]用来表示我希望所有局部变量都被lambda中的值捕获时,是否会导致被复制的函数中的所有局部变量,或者只是lambda使用的所有局部变量?
所以,例如,如果我有:
vector<int> my_huge_vector(100000);
int my_measly_int;
some_function([=](int i){ return my_measly_int + i; });
Run Code Online (Sandbox Code Playgroud)
my_huge_vector会被复制,即使我不在lambda中使用它吗?
我有相当数量的代码,它依赖于捕获shared_from_this()当使用lambda表达式作为回调时确保我的实例保持活动状态:
std::shared_ptr<Thing> self = shared_from_this();
auto doSomething = [this, self] ()
{
// various statements, none of which reference self, but do use this
}
Run Code Online (Sandbox Code Playgroud)
所以问题是:由于我没有self在lambda体内引用,是否允许一致的编译器优化捕获?
考虑以下程序:
#include <functional>
#include <iostream>
#include <memory>
std::function<void ()> gFunc;
struct S : std::enable_shared_from_this<S>
{
void putGlobal()
{
auto self = shared_from_this();
gFunc = [self] { };
}
};
int main()
{
auto x = std::make_shared<S>();
std::cout << x.use_count() << std::endl;
x->putGlobal();
std::cout << x.use_count() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
1 …Run Code Online (Sandbox Code Playgroud)