Home > Blockchain >  Capture shared_ptr in lambda
Capture shared_ptr in lambda

Time:04-28

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;}
   
   ...
   }

CodePudding user response:

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();};

CodePudding user response:

It's better to use weak_ptr instead. Passing this pointer is a trick to solve the problem. The reasons are mentioned here: https://floating.io/2017/07/lambda-shared_ptr-memory-leak/

  • Related