Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

MISRA.CONST.RET.NON_CONST

Constant member function returns non-const pointer to member variable.

MISRA-C++ Rule 9-3-1 (required): const member functions shall not return non-const pointers or references to class-data.

Rationale

When an object is declared with const class type, only const member functions can be invoked on that object. The common expectation of const member functions is that the state of the object may not be modified when invoking the functions. However, returning a non-const pointer or reference to class-data from a const function allows a modification to the conceptual state of an object.

Example

class C
{
public:
   C ( int32_t & b_ ) : a ( new int32_t [ 10 ] ), b ( b_ )
   {
   }
   int32_t * getA () const         // Non-compliant
                                   // Returns non const pointer to data
   {
      return a;
   }
   int32_t * getB () const         // Non-compliant
                                   // Returns non const pointer to data
   {
      return &b;
   }
   const int32_t * getC () const   // Compliant
                                   // Returns const pointer to data
   {
      return &b;
   }
private:
   int32_t * a;
   int32_t & b;
};

void fn ( C const & c )
{
   c.getA()[ 0 ] = 0;   // Modification to conceptual state of C
   *c.getB()     = 0;   // Modification to conceptual state of C
   fn2 ( c.getC() );    // Value can be used,
   *c.getC()     = 0;   // but compiler will report an error here
}