Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[clang-tidy] request: forbid constructing reference_wrapper from reference parameter #117754

Open
mwoehlke-kitware opened this issue Nov 26, 2024 · 0 comments

Comments

@mwoehlke-kitware
Copy link

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

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.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant