Why is std::function trying to call the copy constructor here?

112 Views Asked by At
#include <functional>
struct MyFoo
{
    MyFoo() {}
    MyFoo(const MyFoo&) = delete;
    MyFoo(MyFoo&&) = default;
    MyFoo& operator=(const MyFoo&) = delete;
    MyFoo& operator=(MyFoo&&) = default;
    void operator()(int) {

    }
};

int main(void)
{
    std::function<void(int)> foo{MyFoo()}; 
}

Error   C2280   'MyFoo::MyFoo(const MyFoo &)': attempting to reference a deleted function   

MyFoo is an r-value. When it comes time to take a copy of it, std::function shouldn't copy it but move it.

1

There are 1 best solutions below

11
user17732522 On

std::function always requires the provided callable type to be copy-constructible. What member functions you use is irrelevant.

As for the implementation reason: In order for type erasure as used by std::function to work, all possibly usable functionality must be instantiated for the given callable type at the point of construction, since use sites can't know that this specific callable type may be used in a std::function instance. And std::function permits copying and so this is relevant.