Skip to content

Latest commit

 

History

History
60 lines (50 loc) · 1.56 KB

File metadata and controls

60 lines (50 loc) · 1.56 KB

constParameterReference

Message: Parameter 'x' can be declared as reference to const
Category: Code Quality
Severity: Style
Language: C++

Description

A reference parameter is never used to modify what it refers to, so it could be declared as a reference to const.

Motivation

A missing const hides a guarantee the compiler could otherwise enforce and readers could otherwise rely on: that the function only reads through the reference, never modifies the caller's object through it.

How to fix

Before:

#include <vector>
auto foo(std::vector<int>& vec, bool flag) { // <- 'vec' is only read
    std::vector<int> dummy;
    std::vector<int>::iterator iter;
    if (flag)
        iter = vec.begin();
    else {
        dummy.push_back(42);
        iter = dummy.begin();
    }
    return *iter;
}

After:

#include <vector>
auto foo(const std::vector<int>& vec, bool flag) {
    std::vector<int> dummy;
    std::vector<int>::iterator iter;
    if (flag)
        iter = dummy.begin();
    else {
        dummy.push_back(42);
        iter = dummy.begin();
    }
    return *iter;
}

Related checkers