rspec/rules/S6027/rule.adoc
Arseniy Zaostrovnykh 7ca29f686f Force linebreaks
2021-02-02 15:02:10 +01:00

79 lines
1.9 KiB
Plaintext
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

``++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