GeneralPurpose-LeakingReferenceToTemporary¶
Do not assign a reference or pointer to a temporary object or a subobject thereof
Required inputs: IR
This rule detects when the address of a temporary variable or a subobject thereof is assigned to a longer-living object.
The language prohibits taking the address of an rvalue (i.e. temporary objects and their data members) using the address-of operator. However, it is still possible for a function to return the address of an rvalue expression that binds to one of its arguments.
Bad code (leaking pointer to temporary):
#include <string>
std::string translate(const std::string &);
void display(const char *);
void f() {
std::string str = "Hello, World!";
const char *tr = translate(str).data(); // ERROR: Reference/pointer to temporary object is assigned to longer-lived variable.
display(tr_data);
}
Good code (no temporary):
#include <string>
std::string translate(const std::string &);
void display(const char *);
void f() {
std::string str = "Hello, World!";
std::string tr = translate(str); // OK: tr lives for the remainder of the current scope
display(tr.data());
}
Good code (temporary lifetime within full-expression):
#include <string>
std::string translate(const std::string &);
void display(const char *);
void f() {
std::string str = "Hello, World!";
display(translate(str).data()); // OK: temporary object created by call to translate
// lives until the end of the full expression containing it
}
Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
possibly_leaking_reference_to_temporary_variable |
Reference/pointer to temporary object is assigned to longer-lived variable. |
None |
False |
Options¶
This rule shares the following common options: exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
additional_leaking_functions¶
additional_leaking_functions : set[str] = set()
Alternatively, the functions' definitions in source code can be annotated
as returning a pointer/reference to one of its arguments using the attribute
[[axivion::return_based_on(parameter_name)]], e.g.:
int* f(int &i1, int &i2) [[axivion::return_based_on(i2)]] { return &i2; }
or
struct MyStruct {
int m_i;
int* f() [[axivion::return_based_on(this)]] { return &m_i; }
};
restrict_to_functions¶
restrict_to_functions : set[str] = set()