2021-01-27 13:42:22 +01:00
``++const++`` member functions are the member functions that do not modify the object they are called on.
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
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.
2020-12-21 15:38:52 +01:00
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
When defining a const member function, consider returning by reference/pointer to ``++const++`` or returning by value.
2020-12-21 15:38:52 +01:00
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
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.
2020-12-21 15:38:52 +01:00
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
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.
2020-12-21 15:38:52 +01:00
== 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