Reference to un-named temporary
Local reference is declared by using unnamed temporary variable that a function returns by value
Since R2023a
Description
This defect occurs when:
A function returns an object by value.
You declare a local reference by using the returned unnamed temporary object.
Consider this code:
std::string get(); const std::string &s = get();
get()
returns a string by value. The local reference
s
is declared by using the unnamed temporary string. Polyspace® reports a defect.Risk
Returning an object by copy and then declaring a local reference by using the returned copy can lead to unexpected behavior. For instance, If you later update the code to return the temporary object by reference, perhaps to improve performance, the local reference then resolves to a nonlocal object instead of a local copy. Modifying the nonlocal object causes unexpected results. See Local Reference Declared by Using Unnamed Returned-by-Value Temporary Object.
This defect can lead to inefficiencies in cases where it is possible to use the unnamed temporary object directly instead of using a reference to the temporary object. See Local Reference Used for Passing Object to Function.
Fix
To fix this defect, capture the returned unnamed temporary object by using a variable instead of a reference. When possible, use the unnamed temporary object directly.
Examples
Result Information
Group: Good practice |
Language: C++ |
Default: Off |
Command-Line Syntax:
LOCAL_REF_TO_UNNAMED_TEMPORARY |
Impact: Low |
Version History
Introduced in R2023a
See Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)