79 lines
1.9 KiB
Plaintext
79 lines
1.9 KiB
Plaintext
``++const++`` member functions are the member functions that do not modify the object they are called on.
|
||
|
||
While returning a non-const reference or a pointer from such a function does not in itself modify the object, it creates an opportunity for modification in the future. In particular, it enables the code that uses this member function to modify a ``++const++`` object.
|
||
|
||
|
||
When defining a const member function, consider returning by reference/pointer to ``++const++`` or returning by value.
|
||
|
||
|
||
In some cases you need to be able to read the field from ``++const++`` objects and mutate it in non-``++const++``, as is often the case with container objects, like ``++std::vector++``. Consider using ``++const++``-overloading in this case.
|
||
|
||
|
||
This rule detects when a ``++const++`` member function returns a reference field and has as a return type a pointer/reference to a non-const object.
|
||
|
||
|
||
== Noncompliant Code Example
|
||
|
||
----
|
||
class Person {
|
||
std::string name;
|
||
std::string &alias = name;
|
||
public:
|
||
std::string &getAlias() const { // Noncompliant
|
||
return alias;
|
||
}
|
||
};
|
||
|
||
void fun(const Person &p) {
|
||
p.getAlias() = "Looser"; // The function modifies a constant object
|
||
}
|
||
|
||
class Shadow {
|
||
Person &p;
|
||
public:
|
||
Shadow(Person &p) : p(p) {}
|
||
Person &getPerson() const {// Noncompliant
|
||
return p;
|
||
}
|
||
};
|
||
----
|
||
|
||
|
||
== Compliant Solution
|
||
|
||
|
||
|
||
----
|
||
class Person {
|
||
std::string name;
|
||
std::string &alias = name;
|
||
public:
|
||
std::string const &getAlias() const { // Compliant
|
||
return alias;
|
||
}
|
||
};
|
||
|
||
void fun(const Person &p) {
|
||
//p.getAlias() = "Looser"; // This prank is prevented
|
||
}
|
||
|
||
class Shadow {
|
||
Person &p;
|
||
public:
|
||
Shadow(Person &p) : p(p) {}
|
||
Person const &getPerson() const {// Compliant
|
||
return p;
|
||
}
|
||
Person &getPerson() {// Compliant, const-overload
|
||
return p;
|
||
}
|
||
};
|
||
----
|
||
|
||
|
||
== See
|
||
|
||
* https://isocpp.org/wiki/faq/const-correctness#return-const-ref-from-const-memfn
|
||
|
||
|