dimanche 3 mai 2020

Are there cases where perfect forwarding actually improves performance?

I'm not entirely sure whether I understand perfect forwarding correctly. I've tested the two constructors of the following code:

#include <vector>
#include <utility>

template <typename T>
class myclass {
    public:

    // 1) myclass(T&& a) : myfield(std::forward<T>(a)) {}
    // 2) myclass(T a) : myfield(std::move(a)) {}

    size_t getLength() { return this->myfield.size(); }
    private:
    T myfield;
};


int myfunc() {
    myclass<std::vector<int>> ab({123,23,434,545,65,46456});
    return ab.getLength();
}

and compared the compiled code. It does not seem to make any difference with optimizations. Is there actually a performance gain using perfect forwarding in practice, compared to a normal pass by value followed by a move? Am I using it the wrong way?

Aucun commentaire:

Enregistrer un commentaire