Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access two-step-declared member in lambda setup

Tags:

Don't know how to describe it better. Here's the code. This fails to compiler on gcc 4.9.2 (Debian 8.5), tough I think it compiled in a previous version. The problem seems to occur only if I access the later-declared structure's member as a default argument in the lambda setup. The other shown cases work.

// Test program
class C1
{
private:
    // Forward-declared
    struct S_Private;
    S_Private* d_;

public:
    void func();
};

struct C1::S_Private
{
    int a;
};

void C1::func()
{
    // This will work
    int test = d_->a;

    // Accessing the d_->a as a default argument in lambda setup
    // will NOT work:
    // error: invalid use of non-static data member ‘C1::d_’
    auto some_lambda = [&](int arg = d_->a)
    {
        // This will also work
        int test2 = d_->a;
    };
}

int main(void)
{
}
like image 353
Flo Avatar asked Sep 09 '16 19:09

Flo


People also ask

How do you capture a member variable in Lambda?

To capture the member variables inside lambda function, capture the “this” pointer by value i.e. std::for_each(vec. begin(), vec. end(), [this](int element){ //.... }

Can Lambda access resources across accounts?

Note: A Lambda function can assume an IAM role in another AWS account to do either of the following: Access resources—For example, accessing an Amazon Simple Storage Service (Amazon S3) bucket. Do tasks—For example, starting and stopping instances.

How do I give access to Lambda?

To grant permissions to other accounts or services that aren't available in the Lambda console, you can use the AWS CLI. Add a statement with the add-permission command. The simplest resource-based policy statement allows a service to invoke a function.

Can Lambda functions access within dedicated tenancy VPCs?

Lambda doesn't support running functions in dedicated tenancy VPCs.


1 Answers

Unfortunately in auto some_lambda = [&](int arg = d_->a), d_->a is not the d_->a you used earlier in the function but instead d_->a is being called on the this that you captured using [&]. Because it is a member variable you cannot use it as a default argument in a function.

Essentially

auto some_lambda = [&](int arg = d_->a)
{
    // This will also work
    int test2 = d_->a;
};

Is

struct some_unique_name
{
    some_unique_name(C1*& var) : this_(var) {}
    auto operator()(int arg = this_->d_->a)
    {
        // This will also work
        int test2 = d_->a;
    }
    C1*& this_;
};

auto some_lambda = some_unique_name{this};

As you can see from the translation it uses the class member, not the object in the class itself.

like image 119
NathanOliver Avatar answered Sep 24 '22 16:09

NathanOliver