Search code examples
c++functorstd-function

C++ Return a functor object as std::function


I have a factory method returning a std::function

class Builder {
public:
    function<void(Data&)> build();
}

and a functor object

class Processor {
protected:
    vector<int> content_;
public:
    void operator()(Data&) { 
         ....
    }
}

Now I want to return the functor in the factory method, and I write

function<void(Data&)> build() {
    Processor p;
    // Add items to p.content_

    function<void(Data&)> ret(p);

    return ret;
}

My question is: will ret maintain a copy of p? If so, when p.content_ is large, will that become a burden? What will be a suggested way to implement this?


Solution

  • A std::function hold and own its value. In fact, it requires callable object that are copiable so it can copy it when itself is copied.

    Your function would be perfectly fine like this, and potentially faster:

    function<void(Data&)> build() {
        Processor p;
    
        // fill items
    
        return p; // p moved into the returned std::function (since C++14)
    }
    

    However, if you copy the std::function around, the Processor object will be copied too, so the cost of copying the std::function depends on the type it contains (just as with any type erasure tools)