brintos

brintos / llvm-project-archived public Read only

0
0
Text · 1.3 KiB · 5f1aea1 Raw
33 lines · plain
1.. title:: clang-tidy - readability-reference-to-constructed-temporary2 3readability-reference-to-constructed-temporary4==============================================5 6Detects C++ code where a reference variable is used to extend the lifetime of7a temporary object that has just been constructed.8 9This construction is often the result of multiple code refactorings or a lack10of developer knowledge, leading to confusion or subtle bugs. In most cases,11what the developer really wanted to do is create a new variable rather than12extending 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`` is24assigned 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 list27``{ 1, 2 }``. Both of these examples extend the lifetime of the temporary28object to the lifetime of the reference variable, which can make it difficult29to reason about and may lead to subtle bugs or misunderstanding.30 31To avoid these issues, it is recommended to change the reference variable to a32(``const``) value variable.33