Why is this destructor called 7 times?

Viewed 129

Any idea why this is happening? I am compiling Visual Studio 19

#include <functional>

struct FOO
{
    ~FOO() {
        std::cout << "Destructor called\n";
    }
    void operator()() {}
};
void main()
{
    FOO* foo = new FOO;
    FOO* foo2 = new FOO;
    std::function<void(void)> func = *foo; // Destructor called here, 
}

It calls once during the copy func = *foo; and then when the program exits. I understand that. However:

#include <functional>

struct FOO
{
    
    ~FOO() {
        
        
        std::cout << "Destructor called\n";

    }
    void operator()() {}
};
void main()
{
    FOO* foo = new FOO;
    FOO* foo2 = new FOO;
    std::function<void(void)> func = *foo; // Destructor called here
    
    int breakPoint = 0;

    func = *foo2; // Destructor called 5 times here!!!
    
    breakPoint = 3;

    
}

Called 5 times at func = *foo2; plus one from before, and one on program exit, that's 7 in total. Anybody know where all these destructor calls are coming from? I expected a maybe a temporary created during the copy, that's two copies, and then one when the program exits, that's 3. But 7? And it's strange it's doing it now even in Release mode, the destructor is called 7 times even in Release mode.

Edit: For anyone who doesn't believe I'm getting 7 destructor calls, this is what I run, on Visual Studio 19, both debug, and funny enough Release:

#include <functional>

struct FOO
{
    static inline int count = 0;
    ~FOO() {
        count++;
        std::cout << "Destructor called " << count << " times\n";
    }
    void operator()() {}
};
int main()
{
    FOO* foo = new FOO;
    FOO* foo2 = new FOO;
    std::function<void(void)> func = *foo; // Destructor called here


    func = *foo2; // Destructor called 5 times here!!!


    std::cout << "FOO destructor called " << FOO::count << " times, with another call to come when program exits\n";
}

//Destructor called 1 times
//Destructor called 2 times
//Destructor called 3 times
//Destructor called 4 times
//Destructor called 5 times
//Destructor called 6 times
//FOO destructor called 6 times, with another call to come when program exits
//Destructor called 7 times
0 Answers
Related