Consider this example:
#include <iostream>
struct Thing
{
Thing(int const& ref) : ref(ref) {}
int const& ref;
};
int main()
{
int option_i = 1;
short option_s = 2;
Thing thing_i(option_i);
Thing thing_s(option_s);
std::cout << thing_i.ref << "\n"; // 1
std::cout << thing_s.ref << "\n"; // 2
option_i = 10;
option_s = 20;
std::cout << thing_i.ref << "\n"; // 10
std::cout << thing_s.ref << "\n"; // 2 <<< !!!
}
Now, I understand WHY this is the case: The short
option_s
is converted to an int
using a temporary object. The reference to that temporary is then passed on to the constructor Thing::Thing
, i.e. equivalent to
// Thing thing_s(option_s);
int __temporary = option_s;
Thing thing_s(__temporary);
However, this may in many cases not be desired, as it is very hard to spot the difference. In this case the temporary is at least still alive, but this could easily be a dangling reference-to-temporary as well.
Do you know of any way (design pattern, gcc compiler option, static analysis tool or other) to detect such a const-reference-to-temporary case?
Would you sacrifice const-correctness in order to detect such cases?