What a good way to capture a member variable by value in C ++ 11?

struct myclass {
    myclass(){}
    myclass(int qx):z(qx){   }
    std::function<void()> create() {
        auto px = [z](){
            std::cout << z << std::endl;
        };
        return px;
    }
    int z;
};

myclass my;
my.z = 2;
auto func = my.create();
func();
my.z = 3;
func();

This code will be compiled in gcc 4.6.3, which will correctly make a copy of the member variable z, and both print will receive 2. In gcc 4.8.2, this no longer compiles ..

error: 'this' was not captured for this lambda function

I wonder why this functionality was removed, as it was quite useful.

+4
source share
2 answers

I don't think you can do it directly in C ++ 11 (see @Nawaz comment for a workaround). However, C ++ 14 helps in this case through generalized lambda captures :

auto px = [v = this->z]() // capture by value just ONE member variable
{ 
        std::cout << v << std::endl;
};

Example:

#include <functional>
#include <iostream>

struct myclass {
    myclass(): z{} {}
    myclass(int qx): z(qx) {   }
    std::function<void()> create() {
        auto px = [v = this->z]() {
            std::cout << v << std::endl;
        };
        return px;
    }
    int z;
};

int main()
{
    myclass my;
    my.z = 2;
    auto func = my.create();
    func();
    my.z = 3;
    func();
}

Live on Coliru

+4
source

Lambdas , . -, .

- ++ 14 :

auto px = [z = z](){
    std::cout << z << std::endl;
};

z this->z, , .

++ 14 , , , :

auto z = this->z;
auto px = [z](){
    std::cout << z << std::endl;
};
+2

Source: https://habr.com/ru/post/1627493/


All Articles