64 lines
1.6 KiB
Plaintext
64 lines
1.6 KiB
Plaintext
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.
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
----
|
|
class C
|
|
{
|
|
public:
|
|
C(int32_t & value) : a(&value), b(value) { }
|
|
int32_t * getA () const // Noncompliant, "const" method returns a non-const pointer to data
|
|
{
|
|
return a;
|
|
}
|
|
int32_t & getB () const // Noncompliant, "const" method returns a non-const reference to data
|
|
{
|
|
return b;
|
|
}
|
|
private:
|
|
int32_t * a;
|
|
int32_t & b;
|
|
};
|
|
|
|
void fn ( C const & c )
|
|
{
|
|
c.getA()[ 0 ] = 0; // Hazardous: modification to conceptual state of C from the returned value of a const method
|
|
c.getB() = 0; // Hazardous: modification to conceptual state of C from the returned value of a const method
|
|
}
|
|
----
|
|
|
|
|
|
== Compliant Solution
|
|
|
|
----
|
|
class C
|
|
{
|
|
public:
|
|
C(int32_t & value) : a(&value), b(value) { }
|
|
int32_t const * getA () const // Compliant, "const" method returns a "const" pointer to data
|
|
{
|
|
return a;
|
|
}
|
|
int32_t const & getB () const // Compliant, "const" method returns a "const" reference to data
|
|
{
|
|
return b;
|
|
}
|
|
private:
|
|
int32_t * a;
|
|
int32_t & b;
|
|
};
|
|
|
|
void fn ( C const & c )
|
|
{
|
|
c.getA()[ 0 ] = 0; // Compliant, rejected during compliation
|
|
c.getB() = 0; // Compliant, rejected during compilation
|
|
}
|
|
----
|
|
|
|
|
|
== See
|
|
|
|
* MISRA {cpp}:2008, 9-3-1
|
|
|