[SERVER-84590] Add clang-tidy rule to prevent capturing references from rvalues Created: 05/Jan/24  Updated: 09/Jan/24

Status: Needs Scheduling
Project: Core Server
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Task Priority: Major - P3
Reporter: Vishnu Kaushik Assignee: Backlog - Service Architecture
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
Assigned Teams:
Service Arch
Participants:

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


Generated at Thu Feb 08 06:55:27 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.