Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

free memory of c++ lambda when execute finished

I’m coding a network function on C++, the HTTP request in background thread, use lambda callback when receive HTTP data. But I don’t know how to release the lambda, hopes some help.

void foo()
{
    // the `func` must be a heap variable for asynchronously.
    auto func = new auto ([&](std::string response){
        printf("recv data: %s", response.c_str());
    });
    
    std::thread t([&]{
        sleep(2);   // simulate a HTTP request.
        std::string ret = "http result";
        (*func)(ret);
    });
    t.detach();
    
    // The foo function was finished. bug `func` lambda still in memory ?
}

int main()
{
    foo();
    getchar(); // simulate UI Event Loop.
    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can capture lambda inside a lambda:

void foo()
{
    std::thread t(
        [func = [](std::string response) {
            printf("recv data: %s", response.c_str());
        }](){
        sleep(2);   // simulate a HTTP request.
        std::string ret = "http result";
        func(ret);
    });
    t.detach();
    // The foo function was finished. bug `func` lambda still in memory ?
}

or if it’s supposed to be shared, you can use shared ownership semantics via shared_ptr and then capture it into the lambda by value in order to increase its reference count:

void foo()
{
    auto lambda = [&](std::string response){
                printf("recv data: %s", response.c_str());
            };
    
    std::shared_ptr<decltype(lambda)> func{
        std::make_shared<decltype(lambda)>(std::move(lambda))
    };

    std::thread t([func]{
        sleep(2);   // simulate a HTTP request.
        std::string ret = "http result";
        (*func)(ret);
    });
    t.detach();
}

Of for non-capturing lambdas one can just turn it into a function pointer and don’t really care

void foo()
{
    auto func_{
        [](std::string response){
            printf("recv data: %s", response.c_str());
        }
    };
    
    std::thread t([func=+func_]{ //note the + to turn lambda into function pointer
        sleep(2);   // simulate a HTTP request.
        std::string ret = "http result";
        (*func)(ret);
    });
    t.detach();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading