I found out by chance that I can have a const std::pair<const int, int>& reference to a std::pair<int,int>:
#include <utility>
int main()
{
std::pair<int, int> p{1,2};
const std::pair<const int, int>& ref_ok{p}; // why does this work?
std::pair<const int, int>& ref_invalid{p}; // then why does this not work?
}
Why is this possible, considering that const std::pair<const int, int> and std::pair<int, int> are different types that are not related by inheritance?
const std::pair<const int, int>& ref_ok{p};is actually materializing a temporarystd::pair<const int, int>initialized to the same values aspand the reference initialization is extending the lifetime of the temporary to that of the lifetime of the reference.std::pair<const int, int>& ref_invalid{p};is not allowed because non-constreferences can't bind to a temporary.The following code example shows that
ref_okis not actually a reference top. Changes tophave no effect onref_ok.Output :
Live example : https://godbolt.org/z/8bfM7fYbx