lundi 24 août 2020

what is a correct way to call std::forward

example: (it doesn't assume that func is pure, copy constructible or move constructible)

template<typename Func>
void dispatch(std::vector<int>& cont, Func&& func){
    for (auto& v : cont)
        std::forward<Func>(func)(v);
}

in a standard practice, we should receive a function object by Func&& and then call it by std::forward<Func>(func)(args...), to avoid any copy or move, and choose the correct overload of operator(). but there is a question: what happens if func is a rvalue and its operator() && moves itself?

obviously, a possible result is, the valid but indeterminate func is called, which is an unspecified behavior, I think.

so how to avoid this problem? I think copy constructibility and purity is not an acceptable cost. what about calling operator() & n - 1 times and operator() && once?

Aucun commentaire:

Enregistrer un commentaire