简体   繁体   中英

Pass by value vs. pass by reference in copy assignment operator

First and foremost, there's a similar popular post What is the copy-and-swap idiom? . The accepted answer has a link to https://web.archive.org/web/20140113221447/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/ .

Both the accepted and the linked page state that a commonly used implementation of a copy assignment operator is (copy and pasted from the previous link)

T& T::operator=(T const& x) // x is a reference to the source
{ 
    T tmp(x);          // copy construction of tmp does the hard work
    swap(*this, tmp);  // trade our resources for tmp's
    return *this;      // our (old) resources get destroyed with tmp 
}

but that

T& operator=(T x)    // x is a copy of the source; hard work already done
{
    swap(*this, x);  // trade our resources for x's
    return *this;    // our (old) resources get destroyed with x
}

is better due to copy elision optimizations by the compiler, or in general, always pass by value instead of pass by reference and then copying the parameter passed by reference.

I agree with that the second option is either equivalent or better than the first, but no worse, but I am confused why the first is even written that way in the first place. I do not understand why a temporary variable and a swap was needed.

Instead, couldn't we just have done something like:

T& T::operator=(T const& x) // x is a reference to the source
{ 
    this->member_var = x.member_var;
    //if we have to do a deep copy of something, implement that here
    return *this;
}

which doesn't use a copy constructor.

Your assignment operator is not exception-safe if there are multiple members:

T& T::operator=(T const& x) 
{ 
    this->member_var1 = x.member_var1; 
    this->member_var2 = x.member_var2; // if an exception occurs here, this->member_var1 will still be changed
    return *this;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM