0

Consider a class that is basically an encapsulation of several primitive types.

class sample
{
    int a,b,c,d;
public:
    sample(const sample& s) : a(s.a), b(s.b), c(s.c), d(s.d) {}
    sample(sample&& s) : a(s.a), b(s.b), c(s.c), d(s.d) {}

    //other option (by Value)
    //inline int compute(sample s) 
    //{
    //    return a + b + c + d + s.a + s.b + s.c + s.d;
    //}

    // By references
    inline int compute(const sample& s) 
    {
        return a + b + c + d + s.a + s.b + s.c + s.d;
    }

    inline int compute(sample&& s) 
    {
        return a + b + c + d + s.a + s.b + s.c + s.d;
    }
};

The class overloads compute function for both r-value and l-value references. Here moving the object does not seem to have any benefits over copy.

The only performance gain I can see is that there is no additional copy overhead (As opposed to the single definition that takes argument by value).

Does this implementation make sense? Or should I stick to single function which accepts a value?

Will this implementation cause my binary to increase in size (it should be inlined and hence no-different)

WARhead
  • 643
  • 5
  • 17
  • @Mat Copy overhead as compared to taking by value, which is the other option rather than defining function that takes rvalue and lvalue. (now clarified in question) – WARhead May 14 '20 at 16:08
  • 1
    You can have a single definition by only keeping the const reference overload since it also accepts r-value references. – Empty Space May 14 '20 at 16:11
  • @MutableSideEffect Do I need any cast for binding rvalue references to the const reference overloads? – WARhead May 14 '20 at 16:13
  • No, it is implicit. See https://stackoverflow.com/questions/52104649/c11-rvalue-reference-vs-const-reference. – Empty Space May 14 '20 at 16:14
  • 2
    You don't need those constructors either in this example. Defaults will be just fine. – Mat May 14 '20 at 16:14
  • @Mat Yes I know that, I just added constructors to emphasis that there is no real difference between move and copy for this class – WARhead May 14 '20 at 16:17
  • @MutableSideEffect Ok, Thank you for that, it will make my class much more compact – WARhead May 14 '20 at 16:19

0 Answers0