CppCoreGuidelines icon indicating copy to clipboard operation
CppCoreGuidelines copied to clipboard

Assignment operator takes a value parameter

Open lijh8 opened this issue 7 months ago • 2 comments

On rule of three / five page on cppreference, this assignment operator with a value parameter can replace assignment with both reference and rvalue reference parameter. This makes it rule of four. Can this be mentioned on the core guidelines if it is legal?

rule_of_five& operator=(rule_of_five other) noexcept
{
    std::swap(cstring, other.cstring);
    return *this;
}

cppreference is the only place which has a complete and correct example of rule of five. Such an example is not seen in books like C++ Primer, The C++ Programming Language. Can future editions of these book include a complete and correct example of rule of five. Is not this the core of c++?

ref:

https://en.cppreference.com/w/cpp/language/rule_of_three.html ,

https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#cctor-constructors-assignments-and-destructors , https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-five , https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-copy-assignment , https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-move-assignment ,

lijh8 avatar Jul 08 '25 19:07 lijh8

I believe this is a dup of https://github.com/isocpp/CppCoreGuidelines/issues/1263 which was resolved back then against adding copy-swap assignment to C.21

That said, cppreference discusses the issues with copy/swap assignment, both in the page linked above and in https://en.cppreference.com/w/cpp/language/operators.html#Assignment_operator :

In those situations where copy assignment cannot benefit from resource reuse (it does not manage a heap-allocated array and does not have a (possibly transitive) member that does, such as a member std::vector or std::string), there is a popular convenient shorthand: the copy-and-swap assignment operator

cubbimew avatar Jul 08 '25 21:07 cubbimew

Hi @cubbimew , i think we can have both heap space reuse and copy-and-swap. What do you think about this:

  // https://en.cppreference.com/w/cpp/language/rule_of_three.html ,
  T &operator=(const T &other) {
    auto size = std::strlen(other.cstring);
    if (size != std::strlen(cstring)) {
      *this = T(other);
    } else {
      std::memmove(cstring, other.cstring, size);
    }

    return *this;
  }

lijh8 avatar Jul 10 '25 21:07 lijh8