Add clang-tidy rule to prevent capturing references from rvalues

XMLWordPrintableJSON

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

      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;
      }
      

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

              Created:
              Updated: