Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

valid variable capture from lambda

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

like image 381
lurscher Avatar asked Jun 12 '26 16:06

lurscher


2 Answers

The lambda is not executed until you execute it by writing v() in the Foo constructor. And if you do that, then it is same as if you call the function get() directly from the constructor, which is alright, if get is not a virtual function and you have implemented get in such way that it can be called from the constructor as well. For example, if you do this:

  • Online demo

In this, the implementation of get doesn'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::function instead of boost::function (like I did in my demo)? If your compiler supports lambda, it will support std::function as well, for it's implementation is very trivial.

like image 118
Nawaz Avatar answered Jun 14 '26 04:06

Nawaz


If the lambda function object is stored and not called until the object is fully constructed, then there is no problem. As elsewhere in C++, it is made possible to write code that has undefined behaviour, in order to make it more convenient to take advantage of a subset of cases where the behaviour is defined.

like image 43
Daniel Earwicker Avatar answered Jun 14 '26 05:06

Daniel Earwicker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!