CL.ASSIGN.NON_CONST_ARG

Non-constant object passed to 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.NON_CONST_ARG checker looks for classes that pass a non-constant object to operator=. When this sort of code is 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&);
  };

When the assignment operator returns, it can return either *this or the right-hand side of the operator; for example:

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

This obviously won't compile as it removes the const-attribute from 'rhs' without an explicit const_cast, which would be a bad idea anyway. A possible quick (and ultimately bad) solution for this is simply to declare the 'rhs' parameter as a non-constant reference:

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

Now the code will compile, but this solution makes it impossible for you to assign temporary objects created by the compiler to your class. For instance:

Copy
   class C{
//...
   public:
     C& operator=(C&);
     C(int);
//...
   };
//...
    C obj = 10;

In this case, the compiler will construct a const temporary object for the integer and then attempt to find an assignment operator that accepts that const temporary object as input. Obviously this will fail as only the non-const assignment operator exists. Again, the best advice is to follow the simple, standard template for an assignment operator wherever possible.

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:
       C& operator=(C& rhs){
       return rhs; 
      }
//...
    };

In this example Klocwork finds a CL.ASSIGN.NON_CONST_ARG error in line 3, which breaks the class-construction rule.

Fixed code example

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

In the fixed code example, the operator= returns *this and avoids breaking the rule.