Details
-
Task
-
Resolution: Unresolved
-
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; |
}
|