Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Capture shared_ptr in lambda

I want to capture a shared_ptr in my lambda expression. Tried two methods:

  1. Capture the shared pointer

    error: invalid use of non-static data member A::ptr

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  2. Create a weak pointer and capture it (Found this via some results online). I’m not sure if I’m doing it the right way

    error: ‘const class std::weak_ptr’ has no member named ‘someFunction’

Before anyone flags it as a duplicate, I am aware it might be similar to a some other questions but none of their solutions seem to work for me. Want to know what I’m doing wrong and how to resolve it, that’s why I’m here.

file.h

#include "file2.h"

class A{
   private:
      uint doSomething();
      std::shared_ptr<file2> ptr;
}

file.cpp

#include "file.h"

uint A::doSomething(){
   ...

   // Tried using weak pointer
   //std::weak_ptr<Z> Ptr = std::make_shared<Z>();
   
   auto t1 = [ptr](){
   auto value = ptr->someFunction;}
   
   // auto t1 = [Ptr](){
   // auto value = Ptr.someFunction;}
   
   ...
   }

>Solution :

You cannot capture member directly, either you capture this or capture with an initializer (C++14)

auto t1 = [this](){ auto value = ptr->someFunction();};
auto t1 = [ptr=/*this->*/ptr](){ auto value = ptr->someFunction();};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading