James Campbell
James Campbell

Reputation: 3591

Keep variable around for async lambda

I have a asynchronous lambda in a function. How would I keep a capture variable around.

Psuedo Code:

void hello()
{
    std::string hi( "This is hello" );

    doSomethingThenCallThisLambda([&]
    {
        std::cout << hi;
    });
}

The code above seems to cause memory errors but I am not sure why.

Upvotes: 0

Views: 255

Answers (1)

Marcelo Cantos
Marcelo Cantos

Reputation: 186078

The memory errors are probably due to the fact that hi is destroyed when it goes out of scope. I don't know how doSomethingThenCallThisLambda works, but I'm guessing that it doesn't actually call its parameter directly, but rather stores it somewhere, to be called after hello returns.

You can use a shared_ptr (note the change to pass-by-value):

auto hi = std::make_shared<std::string>("This is hello");

doSomethingThenCallThisLambda([=]
{
    std::cout << *hi;
});

Upvotes: 1

Related Questions