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

additional_leaking_functions

additional_leaking_functions : set[str] = set()

Set of qualified names of functions. Each of these functions will be assumed to return an address that is owned by its first (including this pointer) parameter and must therefore not be dereferenced after the owner is destroyed.

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()

If not empty, check only for leaks that initially occur through the functions given by qualified name here.