c++ - What's a good way to capture member variable by value in c++11? -


this question has answer here:

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 compile in 4.6.3, correct thing make copy of member variable z, , both print 2. in 4.8.2 doesn't compile anymore..

error: ‘this’ not captured lambda function 

i wonder why functionality removed quite useful.

i don't think can directly in c++11 (see @nawaz's comment workaround). however, c++14 helps in instance, via generalized lambda captures:

auto px = [v = this->z]() // capture value 1 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


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -