Std :: function delete-yourself when at the time of calling it?

In some cases, I need to execute the std :: function delete-myself while calling the std :: function:

    std::function<void (void)> test;
    std::shared_ptr<int> tt = std::make_shared<int>(10);
    test = [=,&test]() 
    {
        std::cout << tt.use_count() << std::endl;
        test = nullptr; // destroy self
        return;
    };
    std::cout << tt.use_count() << std::endl;
    tt = nullptr;
    test();

      

This is problem? Because he destroys himself during the challenge. This is ok for vs2015 and xcode. Or should I write like this:

test = [=,&test]() 
    {
        std::shared_ptr<void> raii(nullptr,[&](){ test = nullptr;  }); // destroy itself
        std::cout << tt.use_count() << std::endl;
        return;
    };

      

+3


source to share


1 answer


Your lambda function is basically a closure object that implements its callable operator. This object is copied to std::function

, which uses HEAP for it.

You can check this with the following simple example:

#include <functional>
#include <iostream>
void myTest( std::function<int()> &ref)
{
    static int vs = 4;
    int v = vs;
    ref = [v]()->int{return v;};
    vs++;
}

int main()
{
    std::function<int()> test;

    for (int i=0; i<10; i++)
    {
        myTest(test);
        std::cout << "Another closure call: " << test() << std::endl;
    }

    std::cout << "sizeof function: " << sizeof(test) << std::endl;
}

      

With that in mind and the next question, you could reset this function, of course without worrying about accessing other members.



Is it allowed to delete it?

This is problem? Not unless you are accessing the items.

Or should I write like this: It's safer for you, but not required.

+1


source







All Articles