<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/117754>117754</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            [clang-tidy] request: forbid constructing reference_wrapper from reference parameter
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            clang-tidy
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          mwoehlke-kitware
      </td>
    </tr>
</table>

<pre>
    We (CMake) recently ran into a bug that can be summarized thusly:

```c++
struct Foo {
  Foo(std::string const& ref) : Ref{ref} {}
  void bar() { /* do something with Ref */ }

 std::reference_wrapper<std::string const> Ref;
};

int main()
{
  Foo foo{{}}; // uh-oh
  foo.bar(); // crash
}
```

Passing the reference through a `T [const]&` function parameter bypassed `std::reference_wrapper`'s protection against being constructed from a temporary. Correct code would have `Foo`'s ctor also taking a `std::reference_wrapper<T>` rather than a `T&`. This seems like the sort of thing clang-tidy ought to be able to spot and... discourage.

I propose that clang-tidy should flag construction of a `std::reference_wrapper<T>` from (at least) a `T&`, if the latter is a function parameter, and should recommend changing the parameter type from `T&` to `std::reference_wrapper<T>`. (Ideally this would cover convertible types, but that might be difficult for some potential conversions. Possibly it could at least cover `U&` where `U` is a subclass of `T`.)
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyUVF2PqzYT_jXOzWgRMQGSCy6yuyfSuXilo1en6mU1wADuGpvaQ6L011cDbHarHvVDQgoinpnny4Mxmt4RVSp_VvnrDmcefKjGm6fBvtHTm-EbBtrVvr1XPxMofXz5H76R0icI1JBje4eADoxjDwj13AMPyNCgg5ogzuOIwfxOLfAwR3tX2Vmly1Ok69Mo_SxPeo4c5obh4j2oUj6AvCt9jNxKXSYnjOuh8S6y0gUE6gSJys7wf-pU-SwfytelvHxdOly9aaHGoPRxOVo-g9IXpc_Qeoh-JB6k5c3wID1A6bPSF1jLpcN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