Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  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;}
   
   ...
   }
like image 343
Friday Avatar asked Oct 24 '25 20:10

Friday


1 Answers

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();};
like image 142
Jarod42 Avatar answered Oct 27 '25 09:10

Jarod42