I have a decent amount of code that relies on capturing a shared_from_this()
when using a lambda expression as a callback to ensure that my instance stays alive:
std::shared_ptr<Thing> self = shared_from_this();
auto doSomething = [this, self] ()
{
// various statements, none of which reference self, but do use this
}
So the question is: Since I am not referencing self
inside the lambda body, is a conformant compiler allowed to optimize the capture away?
Consider the following program:
#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;
}
The output is:
1
2
This indicates that g++-4.7.1
does not optimize the capture away (nor does clang-3.1
).