Miscellaneous-NoReferenceToPrivateDataMember

Do not return non-const references to private data members

Required inputs: IR

When a non-const reference to a private data member is handed out to code outside the class, that code could modified the data member in ways that violates the invariants of the class. Data members should be encapsulated: they should be declared as private, and accessor functions should be declared to allow other classes access to the data members.
Example
class C
{
private:
    std::string m_member;

public:
    const std::string& member()
    {
        return m_member;
    }
    void member(const std::string& new_value)
    {
        assert(new_value.size() > 0);
        m_member = new_value;
    }
};
See Also
Rule Miscellaneous-NoPublicDataMembers

Possible Messages

Key

Text

Severity

Disabled

returning_nonconst_member_reference

Return of reference to private non-const data member.

None

False

Options

include_copies_of_pointer_fields

include_copies_of_pointer_fields : bool = False

Whether returning a pointer field should be reported as well.
 

inspect_only_const_methods

inspect_only_const_methods : bool = False

Whether all methods or only const methods should be checked.
 

only_report_references

only_report_references : bool = False

Whether pointer and reference to field should be reported, or just references.
 

smart_pointer_names

smart_pointer_names : set[bauhaus.analysis.config.QualifiedName] = {'std::shared_ptr', 'std::unique_ptr', 'std::weak_ptr'}

Names that are considered smart pointers.