Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-1236

Assignment operators should return non-"const" references

    XMLWordPrintable

    Details

    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way, MISRA C++ 2008 recommended
    • Covered Languages:
      C++
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      20min
    • CppCoreGuidelines:
      C.60, C.63

      Description

      Copy assignment operators and move assignment operators can return anything, including void.

      However, if you decide to declare them yourself (don't forget the "Rule-of-Zero", S4963), it is a recommended practice to return a non-const reference to the left-operand. It allows the developer to chain the assignment operations, increasing consistency with what other types do, and in some cases enabling writing concise code.

      Noncompliant Code Example

      class A {
      public:
        ~A() = default;
        A(A const &) = default;
        A(A&&) = default;
        const A& operator=(const A& other) ; // Noncompliant
        A operator=(A&& other) noexcept; // Noncompliant
      };
      

      Compliant Solution

      class A {
      public:
        ~A() = default;
        A(A const &) = default;
        A(A&&) = default;
        A& operator=(const A& other);
        A& operator=(A&& other) noexcept;
      };
      

      See

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              freddy.mallet Freddy Mallet (Inactive)
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: