【发布时间】:2023-03-16 15:54:01
【问题描述】:
当使用 lambda 表达式作为回调以确保我的实例保持活动状态时,我有相当多的代码依赖于捕获 shared_from_this():
std::shared_ptr<Thing> self = shared_from_this();
auto doSomething = [this, self] ()
{
// various statements, none of which reference self, but do use this
}
所以问题是:由于我没有在 lambda 主体内引用 self,是否允许一致的编译器优化捕获?
考虑以下程序:
#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;
}
输出是:
1
2
这表明g++-4.7.1 没有优化捕获(clang-3.1 也没有)。
【问题讨论】:
标签: c++ lambda c++11 language-lawyer