| 1 |
.. title:: clang-tidy - readability-reference-to-constructed-temporary |
| 2 |
|
| 3 |
readability-reference-to-constructed-temporary |
| 4 |
============================================== |
| 5 |
|
| 6 |
Detects C++ code where a reference variable is used to extend the lifetime of |
| 7 |
a temporary object that has just been constructed. |
| 8 |
|
| 9 |
This construction is often the result of multiple code refactorings or a lack |
| 10 |
of developer knowledge, leading to confusion or subtle bugs. In most cases, |
| 11 |
what the developer really wanted to do is create a new variable rather than |
| 12 |
extending the lifetime of a temporary object. |
| 13 |
|
| 14 |
Examples of problematic code include: |
| 15 |
|
| 16 |
.. code-block:: c++ |
| 17 |
|
| 18 |
const std::string& str("hello"); |
| 19 |
|
| 20 |
struct Point { int x; int y; }; |
| 21 |
const Point& p = { 1, 2 }; |
| 22 |
|
| 23 |
In the first example, a ``const std::string&`` reference variable ``str`` is |
| 24 |
assigned a temporary object created by the ``std::string("hello")`` |
| 25 |
constructor. In the second example, a ``const Point&`` reference variable ``p`` |
| 26 |
is assigned an object that is constructed from an initializer list ``{ 1, 2 }``. |
| 27 |
Both of these examples extend the lifetime of the temporary object to the |
| 28 |
lifetime of the reference variable, which can make it difficult to reason about |
| 29 |
and may lead to subtle bugs or misunderstanding. |
| 30 |
|
| 31 |
To avoid these issues, it is recommended to change the reference variable to a |
| 32 |
(``const``) value variable. |