I’m wondering if the following style of capture by reference is valid:
struct Foo {
Foo( boost::function<void()> v);
int get() const;
};
int main() {
Foo instance( [&]() -> void { int value = instance.get(); .... } );
As you see, i’m capturing a reference to an object being constructed when the lambda is passed. It would seem that if the lambda is called before the constructor fully executes you are accessing a partially constructed object and you get all the danger that represents.
However, is this allowed? it would seem that as long as you make sure you understand when the lambda can be called you should be fine
The lambda is not executed until you execute it by writing
v()in theFooconstructor. And if you do that, then it is same as if you call the functionget()directly from the constructor, which is alright, ifgetis not avirtualfunction and you have implementedgetin such way that it can be called from the constructor as well. For example, if you do this:In this, the implementation of
getdoesn’t require the object to be fully constructed.Also, although it is not related to your question, but still make a note that since you are using C++11 (as implied by the usage of lambda), why don’t you use
std::functioninstead ofboost::function(like I did in my demo)? If your compiler supports lambda, it will supportstd::functionas well, for it’s implementation is very trivial.