Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing C++ code involving *this?

Could someone explain this code? I don't understand line 3:

MyString MyString::operator+(const MyString &str)
{
    MyString ss(*this); //----> explain this part
    ss += str;
    return ss;
}

Thanks!

like image 843
mahyar Avatar asked Dec 04 '22 07:12

mahyar


2 Answers

This code:

MyString ss(*this);

Says "declare a new variable of type MyString that's named ss, and initialize it as a copy of *this." Inside of a member function, this is a pointer to the receiver object (the object that the member function is acting on), so *this is a reference to the receiver object. Consequently, you can read this as "make a new MyString that's called ss and is a copy of the receiver object."

The idiom being used here is implementing operator + in terms of operator +=. The idea is to make a copy of the receiver object, use operator += to add the parameter to the copy, and then to return the copy. It's a widely-used trick that simplifies the implementation of freestanding operators given implementation of the corresponding compound assignment operator.

Hope this helps!

like image 93
templatetypedef Avatar answered Dec 18 '22 09:12

templatetypedef


This is an instance of the common code reuse technique to implement one operator in terms of another.

Suppose we have already defined a compound-plus operator:

class X
{
  X & operator+=(const X&);
};

This unary operator allows us to write a += b, it modifies a and returns a reference to itself. This is all fine and good. Now if we also want to provide a copying, binary plus opearator a + b, which returns a the new value by value and leaves both a and b unchanged, then we want to take advantage of the code we've already written for the compound operator. We do so by calling the unary operator on a temporary copy of a:

X X::operator+(const X & b) const { return X(*this) += b; }
                                           ^^^^^^^^
                                           temporary copy

This is exactly what your code does, only a bit more verbosely. You could as well have written return MyString(*this) += str;

There are other idioms with follow a similar spirit, such as implementing non-const access in terms of const access, copy-assign in terms of copy-construct and swap, and move-assign in terms of move-construct and swap. It always boils down to avoiding code duplication.

like image 37
Kerrek SB Avatar answered Dec 18 '22 08:12

Kerrek SB