1

I have the following code:

class A
{
protected:
    int a
public:
    std::function<void()> lambdaFunc;
    A(std::function<void()> lambdaParam) : lambdaFunc(lambdaParam){}
};

int main()
{
    someFunctionCall(std::shared_ptr<A>(new A([](){ /*I need this to access int a*/  }));
}

I'm not sure how I can give the lambda function in this instance access to the new object?

NeomerArcana
  • 1,978
  • 3
  • 23
  • 50
  • which object do you need to access? – billz Aug 31 '13 at 13:07
  • The new instance of A being created. edit: just so it's clear, I'd like to be able to pass a different "handler" function to different instances. – NeomerArcana Aug 31 '13 at 13:10
  • Remark: I have been recommended to use `make_shared()`. So the call would become `someFunctionCall(std::make_shared([](){ /*...*/ }));` (by the way your original call is missing a closing parenthesis). – gx_ Aug 31 '13 at 13:16
  • you can use the pointer (shared) to the new object A inside somefunctioncall. If you want to pass another `handler`, you create a new instance of A. Otherwise you need a `setter` inside class A. – CS Pei Aug 31 '13 at 13:18
  • @gx_ I've never understood the benefit of make_shared? – NeomerArcana Aug 31 '13 at 13:24
  • 2
    How about passing it as a parameter: http://ideone.com/C6eLjY – Vaughn Cato Aug 31 '13 at 13:28
  • @DavidMurphy http://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Advanced-STL/C9-Lectures-Stephan-T-Lavavej-Advanced-STL-6-of-n#c634479042280000000 'These definitions are equivalent: shared_ptr sp(new T(zero or more args)); auto sp = make_shared(zero or more args); Except that make_shared is (1) significantly more efficient, (2) less verbose when T is 3+ characters, (3) invulnerable to the "unnamed shared_ptr leak".' For (1) know that it can do a single memory allocation (vs two allocations with shared_ptr + new). For (3): http://stackoverflow.com/a/716182 – gx_ Aug 31 '13 at 13:45

1 Answers1

1

I suggest that you pass the this pointer explicitly to the function, something like this (I took the liberty of making a public and initializing it to 0, for simplifying things, but it has nothing to do with your question):

#include <iostream>
#include <functional>
#include <memory>

    class A
    {
    public:
      int a;
    public:
      std::function<void(A& self)> lambdaFunc;
      A(std::function<void(A& self)> lambdaParam) : lambdaFunc(lambdaParam), a(0)
      { /* nothing */ }
    };

    void someFunctionCall(std::shared_ptr<A> p)
    {
      std::cout << p->a << std::endl;
      p->lambdaFunc(*p);
      std::cout << p->a << std::endl;
    }

    int main()
    {
      someFunctionCall(std::shared_ptr<A>(new A([](A&self){ self.a=42; })));
    }

Then, the to call the function for an object a you'll have to write a.lambdaFunc(a), but you can wrap this up in a method, if you think it's not convenient.

The program (in C++11) prints 0, then 42.

nickie
  • 5,608
  • 2
  • 23
  • 37