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