Example results


I am a little bit confused with the results of the second example of section Capturing [*this] in Lambda Expressions

If I modified the code introducing your suggestion to test [*this] :

auto lam = [*this]() { std::cout << s; };

Then I get an error. So I assume that in this case the platform is using a no C++17 compiler.

So, I compiled the example in VS2019 community edition, and then the example works as expected. But then, I have a different result when lambda captures by value [=]. In this case the output of the following code:

auto foo() { return [=] { std::cout << s << '\n'; } };

It prints empty string (due when lambda is created this->s is empty.

Why? As I understand Baz{ “ala” } should initialize s member before foo() call creates lambda and copy this by value.


thanks for the question!

Have a look at the example at:
it’s a bit extended version of the article from the course

When you capture with [this] - then we have undefined behaviour, as the temporary object goes out of scope. So if you call the lambda you cannot be sure what happens. In this case it seems that the variable “s” is located in the same memory place for both objects, and the same value is displayed.

I might be worthy to update the example in the book/course and make it clearer.