Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-84590

Add clang-tidy rule to prevent capturing references from rvalues

    XMLWordPrintableJSON

Details

    • Icon: Task Task
    • Resolution: Unresolved
    • Icon: Major - P3 Major - P3
    • None
    • None
    • None
    • None
    • Service Arch

    Description

      In the below example, a temporary object can return a reference to one of its members, and we are capturing that reference. After the temp object is destroyed, we continue to
      hold on to that reference making it unsafe.

      See comments for more info.

      #include <iostream>
       
      struct MyClassA {
          bool safe;
          MyClassA() {
              safe = true;
          }
          ~MyClassA() {
              std::cout << "Destroying MyClassA." << std::endl;
              safe = false;
          }
      };
       
      struct MyClassB {
          MyClassA _a;
          MyClassA& getMyA() {
              return _a;
          }
      };
       
      MyClassB getTempB() {
          return MyClassB();
      }
       
       
      int main() {
          MyClassA& a = getTempB().getMyA();
          // MyClassB from getTempB() has already been destroyed.
          // And therefore referencing 'a' is unsafe.
          std::cout << "Is 'a' safe to use: " << a.safe << std::endl;
          return 0;
      }
      

      Attachments

        Activity

          People

            backlog-server-servicearch Backlog - Service Architecture
            vishnu.kaushik@mongodb.com Vishnu Kaushik
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

            Dates

              Created:
              Updated: