Issue |
117754
|
Summary |
[clang-tidy] request: forbid constructing reference_wrapper from reference parameter
|
Labels |
clang-tidy
|
Assignees |
|
Reporter |
mwoehlke-kitware
|
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`.)
_______________________________________________
llvm-bugs mailing list
llvm-bugs@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs