Confusing C ++ code including * this?

Can someone explain this code? I do not understand line 3:

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

Thanks!

+4
source share
5 answers

This code:

 MyString ss(*this); 

Says "declares a new variable of type MyString named ss and initializes it as a copy of *this ." Inside a member function, this is a pointer to a receiver object (the object that the member function acts on), so *this is a reference to a receiver object. Therefore, you can read it as "create a new MyString called ss and is a copy of the recipient object."

The idiom used here implements operator + in terms of operator += . The idea is to make a copy of the recipient object, use operator += to add the parameter to the copy, and then to return the copy. This is a widely used trick that simplifies the implementation of autonomous operators when implementing the corresponding compound assignment operator.

Hope this helps!

+11
source

This is an example of a method for reusing common code to implement one operator in terms of another.

Suppose we have already defined the complex-plus operator:

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

This unary operator allows you to write a += b , it modifies a and returns a reference to itself. All is well and good. Now, if we also want to provide a copy, the binary plus opearator a + b , which returns a new value by value and leaves both a and b unchanged, then we want to use the code that we already used for the complex operator. We do this by calling the unary operator on a temporary copy of a :

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

This is exactly what your code does, only in a bit more detail. You could write return MyString(*this) += str;

There are other idioms that follow a similar spirit, such as implementing non-constant access in terms of access to const, copy-assignment in terms of copy-construct and swap, and transfer-assignment in terms of move-construct and swap. It always comes down to Avoid duplication of code.

+3
source

This is a constructor for MyString , which takes as an argument the value of the current object (of type MyString ).

+1
source

From what I can tell, this is a copy constructor that creates a new MyString with the contents of the current MyString object.

+1
source

ss is a new line that is created using the copy constructor from the original line.

+1
source

All Articles