0

I want to overload the == operator for a simple struct

struct MyStruct {
public:
   int a;
   float b;
   bool operator==( ) {  }
}

All the examples I'm seeing seem to pass the value by reference using a &.

But I really want to pass these structs by value.

Is there anything wrong with me writing this as

bool operator== (MyStruct another) { return ( (a==another.a) && (b==another.b) ); } 
interstar
  • 26,048
  • 36
  • 112
  • 180
  • 1
    *But I really want to pass these structs by value*, Why? – NathanOliver Mar 20 '19 at 18:32
  • Because I'm doing it everywhere else in the program, and I wanted to be consistent, rather than having to think about when I'm passing by reference and when I'm passing by value. The == operator doesn't change the struct, so there's no need for it to be passed by reference. – interstar Mar 20 '19 at 18:35
  • 1
    Invoking copy constructors for a comparison would be a waste of resources. Your operator won't look any different at use. Maybe you should rethink your strategy? – lakeweb Mar 20 '19 at 18:41
  • related/dupe: https://stackoverflow.com/questions/270408/is-it-better-in-c-to-pass-by-value-or-pass-by-constant-reference – NathanOliver Mar 20 '19 at 18:45

2 Answers2

1

It should really not matter expect that you pay the penalty of a copy when you pass by value. This applies if the struct is really heavy. In the simple example you quote, there may not be a big difference.

That being said, passing by const reference makes more sense since it expresses the intent of the overloaded function == clearly. const makes sure that the overloaded function accidentally doesn't modify the object and passing by reference saves you from making a copy. For == operator, there is no need to pass a copy just for comparison purposes.

If you are concerned about consistency, it's better to switch the other pass by value instances to pass by const ref.

Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125
1

While being consistent is laudable goal, one shouldn't overdo it. A program containing only 'A' characters would be very consistent, but hardly useful. Argument passing mechanism is not something you do out of consistency, it is a technical decision based on certain technical aspects.

For example, in your case, passing by value could potentially lead to better performance, since the struct is small enough and on AMD64 ABI (the one which is used on any 64bit Intel/AMD chip) it will be passed in a register, thus saving time normally associated with dereferencing.

On the hand, in your case, it is reasonable to assume that the function will be inlined, and passing scheme will not matter at all (since it won't be passed). This is proven by codegen here (no call to operator== exist in generated assembly): https://gcc.godbolt.org/z/G7oEgE

SergeyA
  • 61,605
  • 5
  • 78
  • 137