4

In some case, I have to std::function delete-itself during std::function call :

    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();

is it will be a problem ? Because it destroy it-self during its call.It's OK for vs2015 and xcode. Or I should write like this :

test = [=,&test]() 
    {
        std::shared_ptr<void> raii(nullptr,[&](){ test = nullptr;  }); // destroy itself
        std::cout << tt.use_count() << std::endl;
        return;
    };
NeoLiu
  • 212
  • 3
  • 11
  • What do you want to achieve by clearing the `std::function` object? It should not release a significant amount of memory. The actual machine code of the function can't be deleted (easily). – chtz May 10 '17 at 06:52
  • I just write some test code. In my project, I came across one case like this. I just wanna know, if i call std::function and destroy itself during its call. Will it be a problem ? – NeoLiu May 10 '17 at 07:00
  • It seems that this situation is largely equivalent to [calling `delete this` from a member function](http://stackoverflow.com/questions/3150942/is-delete-this-allowed): For stateful lambdas and function objects, the `std::function` has ownership which is released by the `nullptr` assignment. This happens within a member function call to `operator()()` on the function object. – ComicSansMS May 10 '17 at 10:35

1 Answers1

1

Your lambda function is basically a closure object implementing its callable operator. This object is copied into the std::function which use the HEAP for it.

You might test 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;
}

Considering that, and the following question, you could reset the function, of course, taking care of not accessing further members.

Is delete this allowed?

is it will be a problem ? Not if you do not access members.

Or I should write like this? It is more secure for yourself, but not required.

Community
  • 1
  • 1
Adrian Maire
  • 14,354
  • 9
  • 45
  • 85