14

I recently struggled with a bug hard to find for me. I tried to pass a lambda to a function taking a std::function object. The lambda was capturing a noncopyable object.

I figured out, obviously some copy must happen in between all the passings. I came to this result because I always ended in an error: use of deleted function error.

Here is the code which produces this error:

void call_func(std::function<void()> func)
{
    func();
}

int main()
{
    std::fstream fs{"test.txt", std::fstream::out};
    auto lam = [fs = std::move(fs)] { const_cast<std::fstream&>(fs).close(); };
    call_func(lam);
    return 0;
}

I solved this by capseling the std::fstream object in an std::shared_ptr object. This is working fine, but I think there may be a more sexy way to do this.

I have two questions now:

  1. Why is this error raising up?
  2. My idea: I generate many fstream objects and lambdas in a for loop, and for each fstream there is one lambda writing to it. So the access to the fstream objects is only done by the lambdas. I want do this for some callback logic. Is there a more pretty way to this with lambdas like I tried?
9
  • 10
    /OT: Don't use const_cast, instead mark your lambda as mutable.
    – Rakete1111
    Sep 15, 2018 at 13:11
  • BTW, your const_cast is UB. You can't modify objects that were casted this way. The correct way to do this, as Rakete1111 pointed out, is to mark the object mutable Sep 15, 2018 at 13:18
  • Why I have to make it mutable?
    – JulianW
    Sep 15, 2018 at 13:18
  • @CássioRenan What is UB here? The member variable is captured as non-const; it is only the generated operator() that is marked const. Casting away const from a const lvalue to a non-const object to modify said object is completely fine - and the entire point of const_cast. Sure, it's not good style here, I don't think, but it's not UB. Or if it is, why? Sep 17, 2018 at 7:13
  • @JulianH because that is how to get an operator() that is not const-qualified and hence provides read-write access to the capture members of the lambda. Sep 17, 2018 at 7:15

1 Answer 1

12

The error happens because your lambda has non-copyable captures, making the lambda itself not copyable. std::function requires that the wrapped object be copy-constructible.

If you have control over call_func, make it a template:

template<typename T>
void call_func(T&& func)
{
    func();
}

int main()
{
    std::fstream fs{"test.txt", std::fstream::out};
    auto lam = [fs = std::move(fs)] { const_cast<std::fstream&>(fs).close(); };
    call_func(lam);
}

Following is my take on your idea in (2). Since std::function requires the wrapped object to be copy-constructible, we can make our own function wrapper that does not have this restriction:

#include <algorithm>
#include <fstream>
#include <iterator>
#include <utility>
#include <memory>
#include <sstream>
#include <vector>

template<typename T>
void call_func(T&& func) {
    func();
}

// All functors have a common base, so we will be able to store them in a single container.
struct baseFunctor {
    virtual void operator()()=0;
};

// The actual functor is as simple as it gets.
template<typename T>
class functor : public baseFunctor {
    T f;
public:
    template<typename U>
    functor(U&& f)
        :    f(std::forward<U>(f))
    {}
    void operator()() override {
        f();
    }
};

// In C++17 you don't need this: functor's default constructor can already infer T.
template<typename T>
auto makeNewFunctor(T&& v) {
    return std::unique_ptr<baseFunctor>(new functor<T>{std::forward<T>(v)});
}

int main() {
    // We need to store pointers instead of values, for the virtual function mechanism to behave correctly.
    std::vector<std::unique_ptr<baseFunctor>> functors;

    // Generate 10 functors writing to 10 different file streams
    std::generate_n(std::back_inserter(functors), 10, [](){
        static int i=0;
        std::ostringstream oss{"test"};
        oss << ++i << ".txt";
        std::fstream fs{oss.str(), std::fstream::out};
        return makeNewFunctor([fs = std::move(fs)] () mutable { fs.close(); });
    });

    // Execute the functors
    for (auto& functor : functors) {
        call_func(*functor);
    }
}

Note that the overhead from the virtual call is unavoidable: Since you need functors with different behavior stored in the same container, you essentially need polymorphic behavior one way or the other. So you either implement this polymorphism by hand, or use virtual. I prefer the latter.

17
  • There's nothing wrong with a mutable lambda if it's known that it will run just once. For example, there's no risk in pushing a mutable lambda to a work queue. Sep 15, 2018 at 13:48
  • First, thanks a lot, but auto lam = [fs = std::move(fs)] () mutable { fs.close(); }; call_func(lam); does end in the same error for me. and your other solutions doesn't fit cause the std::fstream objects is longly out of scope when the lambdas are getting invoked.
    – JulianW
    Sep 15, 2018 at 13:50
  • 1
    @JulianH I'm sorry, I didn't understand your question. You can move a copyable object into the lambda and you will be able to use it with std::function normally. e.g: just because you're moving the object, this does not mean the object must be not copyable. I edited my answer with my take on your idea in (2) Sep 15, 2018 at 14:54
  • 1
    @underscore_d You're correct. Edited answer to remove unnecessary changes in OP's code. Sep 17, 2018 at 17:07
  • 1
    @underscore_d To be honest, I don't consider any of the two to be good style. But that's just me. There's just too many ways for subtle changes to introduce silent bugs. I cited one of those ways when responding to a comment by François, above. Also, const_cast has the added problem that if you actually do pass the lambda a const object, it will cause UB instead of causing a compiler error (as a mutable lambda would). Sep 17, 2018 at 18:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.