2016-06-08 9 views
9

मैं स्थानीय चर को लैम्ब्डा के कब्जे में ले जाने की कोशिश कर रहा हूं।सी ++ कैप्चर लेवल प्रारंभिक है?

#include <thread> 
#include <iostream> 

// Moveable but not copyable object. 
class WorkUnit 
{ 
    public: 
     WorkUnit(int)        {} 
     WorkUnit(WorkUnit&&)   noexcept {} 
     WorkUnit& operator=(WorkUnit&&) noexcept {return *this;} 
     WorkUnit(WorkUnit const&)     = delete; 
     WorkUnit& operator=(WorkUnit const&)  = delete; 

     // Non const function. 
     void doWork() 
     { 
      std::cerr << "Work\n"; 
     } 
}; 

int main() 
{ 
    WorkUnit data(4); 

    // Use C++14 generalized lambda capture. 
    std::thread test([data{std::move(data)}]() 
     { 
      // here it is complaining the `data` is a const value. 
      // Is there a way to capture this as a non const? 
      data.doWork(); 
     } 
    ); 
    test.join(); 
} 

जब मैं संकलित करता हूं तो मुझे यह मिलता है।

> g++ -std=c++14 WU.cpp 
Test.cpp:26:13: error: member function 'doWork' not viable: 'this' argument has type 'const WorkUnit', 
     but function is not marked const 
      data.doWork(); 
      ^~~~ 

मैं पर कब्जा कर लिया मूल्य कोई स्थिरांक होने की उम्मीद कर रहा था।

+4

रखें 'mutable' के बाद' [डेटा = std :: चाल (डेटा)]()/* यहाँ */{ ' –

+0

या संदर्भ से यह कब्जा:' [और डेटा]() { डेटा ।काम करो(); } '। – skypjack

+0

@PiotrSkotnicki क्यों शुरुआतकर्ता को अनुमति नहीं है? – songyuanyao

उत्तर

6

आप mutable इस्तेमाल कर सकते हैं:

परिवर्तनशील - अनुमति देता है शरीर मापदंडों प्रतिलिपि द्वारा कब्जा कर लिया संशोधित करने के लिए, और जब तक कीवर्ड mutable में इस्तेमाल किया गया था उनके गैर स्थिरांक सदस्य कार्यों

कॉल करने के लिए लैम्ब्डा-अभिव्यक्ति, फ़ंक्शन-कॉल ऑपरेटर कॉन्स्ट-क्वालिफाइड है और ऑब्जेक्ट्स प्रतिलिपि द्वारा कैप्चर की गई हैं, इस operator() के अंदर से गैर-संशोधित हैं।

std::thread test([data{std::move(data)}]() mutable 
    { 
     // the function-call operator is not const-qualified; 
     // then data is modifiable now 
     data.doWork(); 
    } 
); 
+0

की अनुमति है जो कॉपी को उत्परिवर्तनीय करने की अनुमति देता है, मूल को संशोधित नहीं करता है। – Ajay

+0

@ अजय हाँ, आप सही हैं। मुझे लगता है कि ओपी मूल 'डेटा' को संशोधित नहीं करना चाहता क्योंकि उसने इसे स्थानांतरित कर दिया है। – songyuanyao

संबंधित मुद्दे