Move semantics for a plurality of constructor parameters

83 views Asked by At

An object's constructor requires twp arguments from the user. It is required that the parameters may be of different types, but each type may be assumed to implement proper move-semantics. (The actual example is a cubic_spline class, that is constructed using random-access objects [vectors] of numerical data, one for the "x's", the other for the "y's" or "f(x)'s".)

It is further required that the user may pass either parameter either to be copied by the object, or captured without copying via move-semantics.

The following works for both VC++ std::vector (Dinkumware) and for a custom container that I wrote. Is it really this simple? I think the code below is probably correct, but I have sneaking doubts. My question is simply, "Is this correct code?" (And if not, how can it fail, and how should it be rewritten? An unnecessary copying of the data would be considered a fail.)

#include <vector>

template<class V1, class V2>
class spline {
public:

    spline(V1 v1, V2 v2)  noexcept
    : xv( std::move(v1))
    , yv( std::move(v2))
    {}

private:
    V1 xv;
    V2 yv;
};


int main() {

    using dv = std::vector<double>;
    using fv = std::vector<float>;

    fv xx { 1.f, 1.5f, 1.7f, 2.f};
    dv yy { 1, -1, 1.2, 3};
    spline<fv, dv> sp(xx, std::move(yy));
    // xx is now unchanged, but yy is empty, its contents
    // having been moved by sp.
    return 0;
}
1

There are 1 answers

2
Super-intelligent Shade On BEST ANSWER

This is correct code. This is the beauty of C++11. For further data please see Dave Abrahams' post Want speed? Pass by value.