0

Which way more effective? Is there any difference this->X or just X? I think it 'void' version bcs compilator dont need to call contructor or smth, just add.

void operator+=(vect right)
{
    this->x += right.x;
    this->y += right.y;
}

void operator+=(vect right)
{
    x += right.x;
    y += right.y;
}

vect& operator+=(vect right)
{
    x += right.x;
    y += right.y;
    return *this;
}
Kelbon
  • 29
  • 6
  • There is no difference between x and this->x, in your context, it would only help if you had the same variables passed in somewhere else in the function or used within that function with the same name. To avoid this you can usually prepend a m_ before member variables so you know that you are manipulating the class member variable. so m_x += right.x. – Omid CompSCI Feb 26 '20 at 07:54
  • 1
    When in doubt you can always check your code in [compiler explorer](https://godbolt.org) – hoo2 Feb 26 '20 at 08:02

2 Answers2

6

Start by not taking complex types as arguments by value if you care about efficiency.

vect& operator+=(vect const& right)
{
    x += right.x;
    y += right.y;
    return *this;
}

this->x and just a plain x mean the same thing. They don't affect runtime at all. And finally, return vect& because it's idiomatic.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
3

Version 1 and 2 do the exact same thing, no difference. Version 3 allows you to write

vecA += vecB += vecC += vecD;

There is no difference in terms of performance, the operator returns a reference to self, not a new object.

Timo
  • 9,269
  • 2
  • 28
  • 58
  • Re: "Version 3 allows you to write ..." -- so you're saying that Version 3 is a bad idea? I have no idea what that code actually does, and no interest in figuring it out. +1. – Pete Becker Feb 26 '20 at 14:17
  • @PeteBecker I wouldn't recommend it but you certainly can do it. Too see what happens look at [this](https://godbolt.org/z/bDo2Ru). Basically we sum the values from right to left and store each intermediate result in the left operand of each operation. – Timo Feb 26 '20 at 14:22