Clang tidy rule to prevent function_ref from being assigned to

    • Type: Task
    • Resolution: Unresolved
    • Priority: Major - P3
    • None
    • Affects Version/s: None
    • Component/s: None
    • None
    • Server Programmability
    • None
    • None
    • None
    • None
    • None
    • None
    • None

      Recently I was bitten by this:

      using GenerateTimestampsFn = function_ref<Timestamp(uint64_t nticks)>;
      
      void doSomethingOnVector(const std::vector<BSONObj>& entries, GenerateTimestampsFn timestampFn) {
          ...
          timestampFn(entries.size());
      }
      
      // Call site
      void main() {
          // This line is problematic! 'f' is a function_ref and the object it's pointing
          // to will be destroyed.
          GenerateTimestampsFn f = [&](uint64_t nticks) {
              return Timestamp(100, 1);
          };
      
          doSomethingOnVector(entries, f);
      }
      
      

      f is dangling.

      The fix here is:

      void main() {
          // Using `auto` now.
          auto f = [&](uint64_t nticks) {
              return Timestamp(100, 1);
          };
      
          doSomethingOnVector(entries, f);
      }
      

      So either let's make sure we're not using function_ref the way I did, or what james.bronsted@mongodb.com said, let's ban function_ref altogether.

            Assignee:
            Unassigned
            Reporter:
            Vishnu Kaushik
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: