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.RET.REF.NON_CONST

Member function returns non-const reference to member variable.

MISRA-C++ Rule 9-3-2 (required): Member functions shall not return non-const handles to class-data.

Rationale

By implementing class interfaces with member functions the implementation retains more control over how the object state can be modified and helps to allow a class to be maintained without affecting clients. Returning a handle to class-data allows for clients to modify the state of the object without using any interfaces.

Example

class C

{
public:
   int32_t & getA ()   // Non-compliant
   {
      return a;
   }
private:
   int32_t a;
};

void b ( C & c )
{
   int32_t & a_ref = c.getA ();
   a_ref = 10;   // External modification of private C::a
}

'c.getA()' returns a reference to the member, which is then stored and modified by 'a_ref'. The class, therefore, has no control over changes to its state.

Where a resource is used by the class, but is not class-data, non-const handles to this data may be returned.

class C

{
public:
   C ( int32_t * shared ) : m_shared ( shared )
   {
   }
   int32_t * getA ()
   {
      return m_shared; // Compliant - m_shared is not class-data
   }
private:
   int32_t * m_shared;
};