Skip to content

False positive -Wshadow-field-in-constructor-modified on reference parameter #162494

@aaronpuchert

Description

@aaronpuchert

Compile this code with -Wshadow:

struct S {
    int &x;
    S(int &x) : x(x) { ++x; }
};

We get the warning:

<source>:3:24: warning: modifying constructor parameter 'x' that shadows a field of 'S' [-Wshadow-field-in-constructor-modified]
    3 |     S(int &x) : x(x) { ++x; }
      |                        ^
<source>:3:12: note: variable 'x' is declared here
    3 |     S(int &x) : x(x) { ++x; }
      |            ^
<source>:2:10: note: previous declaration is here
    2 |     int &x;
      |          ^

But we're not actually modifying the parameter: the parameter is a reference (and binds to the same object as the member).

However, it's not clear if we should suppress the warning if the parameter is a reference, or only if both parameter and member are references. If the member is not a reference, the intention might have been to modify the member instead of the object bound by the parameter reference.

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:diagnosticsNew/improved warning or error message in Clang, but not in clang-tidy or static analyzerfalse-positiveWarning fires when it should not

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions