0

Say I have the following class:

class test {
    A a;
    B b;
    C c;

    public:
    test(A const& a_in, B const& b_in, C const& c_in) : a(a_in), b(b_in), c(c_in){}
}

Now, if any of the parameters to the constructor are rvalue references, I would obviously want to use move semantics instead of copying. However, since each parameter might (or might not) be passed in as an rvalue reference, this means I would have to write eight different constructors, one for each possible combination of rvalue references:

class test {
    A a;
    B b;
    C c;

    public:
    test(A const& a_in, B const& b_in, C const& c_in) : a(a_in), b(b_in), c(c_in){}
    test(A const& a_in, B const& b_in, C &&c_in)      : a(a_in), b(b_in), c(c_in){}
    test(A const& a_in, B &&b_in,      C const& c_in) : a(a_in), b(b_in), c(c_in){}
    test(A const& a_in, B &&b_in,      C &&c_in)      : a(a_in), b(b_in), c(c_in){}
    test(A &&a_in,      B const& b_in, C const& c_in) : a(a_in), b(b_in), c(c_in){}
    test(A &&a_in,      B const& b_in, C &&c_in)      : a(a_in), b(b_in), c(c_in){}
    test(A &&a_in,      B &&b_in,      C const& c_in) : a(a_in), b(b_in), c(c_in){}
    test(A &&a_in,      B &&b_in,      C &&c_in)      : a(a_in), b(b_in), c(c_in){}
}

Even for just three parameters, this is already a terrible mess. Is there a better way?

Marco Merlini
  • 875
  • 7
  • 29
  • 2
    given that all your parameters are sinks, you should accept by value and move them into the members – kmdreko Sep 04 '18 at 00:34
  • @kmdreko Depends. By default, definitely yes. But accepting by value costs an extra move, which is not necessarily cheap. Forwarding is the perfect solution in terms of absolute performance (although not in terms of implementation niceness). – Justin Sep 04 '18 at 00:40

0 Answers0