Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is copy assignment operator with copy and swap idiom and self assignment check recommended?

Here you can see copy assignment operator implementation with self assignment check:

String & operator=(const String & s)
{
    if (this != &s)
    {
        String(s).swap(*this); //Copy-constructor and non-throwing swap
    }

    // Old resources are released with the destruction of the temporary above
    return *this;
}

This is good for self assignment, but bad for performance:

  1. as each time it check as if statement (I don't know how much will be it optimal, considering the branch prediction)
  2. Also we lose here copy elision for rvalue arguments

So I still don't understand if I would implement std::vector's operator= how I would implement it.

like image 490
Narek Avatar asked May 09 '16 20:05

Narek


1 Answers

Yes, this code is superflous. And it is true that it is causing extra unncessary branch. With proper swap and move semantics, following should be much more performant:

String& String::operator=(String s) { // note passing by value!

    std::swap(s, *this); // expected to juggle couple of pointers, will do nothing for self-assingment
    return *this;
}

Also note, it is more benefical to accept the argument by value.

like image 55
SergeyA Avatar answered Oct 15 '22 10:10

SergeyA