mercredi 26 octobre 2016

Force an object to be passed as copy to a function receiving a universal reference

I'm trying to pass a local lambda function to a std::bind (for passing to a connect function of a signal):

void f()
{
    auto signal_f = [this](int, int) { /* ... */ };

    namespace ph = std::placeholders;
    signal.connect(std::bind(signal_f, ph::_1, ph::_2));
}

But the function parameter of std::bind is received as a universal reference:

template<class F, class... Args>
/* unspecified */ bind(F&& f, Args&&... args);

So, since my lambda object is a named object, it's passed as a lvalue reference , but my lambda object will be destroyed after f() exists, potentially causing memory leaks when the signal is emited.

What is the simplest way of passing that object by copy?

Of course, I could do always things like:

signal.connect(std::bind<std::decay(decltype(signal_f))::type>
   (signal_f, ph::_1, ph::_2));

of other tricky ways but they are too cumbersome, so, what is the simplest way of doing it?

NOTE: Is there any function from the standard library to create a copy, something like std::make_rvalue(o) or a std::copy version for objects instead of for containers?

Aucun commentaire:

Enregistrer un commentaire