CL.ASSIGN.RETURN_CONST

Constant object returned in assign operator=

This is a class-level (CL) checker that notifies you of a potentially limiting or unwise design choice in the parameter type of the assignment operator. Class-level checkers produce recommendations based on Scott Meyer's rules for effective C++ class construction.

The CL.ASSIGN.RETURN_CONST checker looks for classes containing assignment operators that return const references. When such return types are used, certain language constructs are impossible to express. Whether those language constructs are desirable or otherwise is debatable, but following the basic template below guarantees that language consistency can be maintained regardless of type:

Copy
  class MyClass {
  public:
    MyClass& operator=(const MyClass&);
  };

Vulnerability and risk

There is no vulnerability exposed through this design choice, but the risk is that unfamiliar programmers will attempt to use language constructs that "should" work but are incompatible, and be faced with compiler warnings that may make little or no sense (given the usual complexity of C++ compiler output).

Vulnerable code example

Copy
    class C {
    public:
      const C& operator=(const C& rhs); // const return type
...
    }; 

    void foo(const C& tmpl) {
      C obj;
      (obj = tmpl).someNonConstMethod();
    }

In this example, Klocwork reports a CL.ASSIGN.RETURN_CONST error on line 3. The outcome of this design choice is a compiler error detailing that the attempt to use the assignment operator within class 'C' on line 9 is illegal. The Klocwork warning allows you to re-assess the code and avoid a limiting design in the return type.

Fixed code example

Copy
    class C {
    public:
      C& operator=(const C& rhs); 
... 
    };

    bool foo(const C& tmpl) { 
      C obj;
      (obj = tmpl).someNonConstMethod();
    }

In the fixed code example, line 3 uses the standard template for an assignment operator, ensuring that the attempt to use it on line 9 will work as expected.