我有相当数量的代码依赖于shared_from_this()
在使用 lambda 表达式作为回调时捕获 a 以确保我的实例保持活动状态:
std::shared_ptr<Thing> self = shared_from_this();
auto doSomething = [this, self] ()
{
// various statements, none of which reference self, but do use this
}
所以问题是:由于我没有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;
}
输出是:
1
2
这表明g++-4.7.1
没有优化捕获(也没有clang-3.1
)。