Main Content

MISRA C++:2008 Rule 14-5-3

A copy assignment operator shall be declared when there is a template assignment operator with a parameter that is a generic parameter

Description

Rule Definition

A copy assignment operator shall be declared when there is a template assignment operator with a parameter that is a generic parameter.

Rationale

When declaring a user-defined assignment operator, the corresponding implicit operator is suppressed. When declaring a template assignment operator that has a generic parameter, this behavior is not preserved. In that case, to suppress the implicit shallow-copying operator, explicitly instantiate a version of the copy assignment operator for the class.

If you do not declare the copy assignment operator for the class, the compiler-generated copy assignment operator might be used instead on implementation. Not declaring a copy assignment operator explicitly might result in an unexpected outcome, such as creating a shallow copy when a deep copy was intended.

Polyspace Implementation

Polyspace® flags this checker if a structure, class, or union contains a template assignment operator that has a generic parameter but no copy assignment operator is present within the structure, class, or union.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include<cstdint>
namespace example
{
  class A  //Noncompliant               
  {
    public:		
	  
      template <typename T>
      T & operator= ( T const & rhs ) 
      {
        if ( this != &rhs ) {
          delete i;
          i = new int32_t;
          *i = *rhs.i;
        }
        return *this;
      }
    private:
      int32_t * i;      // Member requires deep copy
  };
  
  void f ( A const & a1, A & a2 )
  {
    a2 = a1;   
  }
};

Because no copy assignment operator is declared within the class, Polyspace flags class A. The implicitly defined copy assignment operator is not suppressed by the template assignment operator and results in a shallow copy of a1 to a2 when you might want a deep copy.

#include<cstdint>
namespace example
{
  class A//Compliant                 
  {
    public:
      A & operator= (A const & rhs) {};
	  
      template <typename T>
      T & operator= ( T const & rhs )
      {
        if ( this != &rhs ) {
          delete i;
          i = new int32_t;
          *i = *rhs.i;
        }
        return *this;
      }
    private:
      int32_t * i;
  };
  
  void f ( A const & a1, A & a2 )
  {
    a2 = a1;   
  }
};

Because this class contains a copy assignment operation declaration, Polyspace does not flag class A.

Check Information

Group: Templates
Category: Required

Version History

Introduced in R2013b