Consider
#include <iostream>
#include <utility>
const auto& foo() {
return std::make_pair("hi there", 2020);
}
int main()
{
//const auto& p = std::make_pair("hi there", 2020); // Okay, just warning, no segfault
const auto& p = foo(); // Oops, segmentation fault
std::cout << "The value of pair is:\n"
<< "(" << p.first << ", " << p.second << ")\n";
}
It's very curious that if we just bind a const reference to a temporary it will be "fine", though with returning reference to temporary
warning; while if we try the second one (via delegation) we would highly likely get a segmentation fault error (I tested it on Ubuntu 20.04 LTS with g++ 10.2.0 -std=c++17
as well as some online compilers, e.g. on coliru. But on VS2019 release mode it can run without segfault which may due to its lazy check/protection for optimization) So, ..., what's wrong with the delegation?
It's not the delegation, per se, that's the problem, but the function to which you delegate: that function returns a reference to a local object, which will cease to exist by the time the calling routine gets hold of it (or tries to).
You code, taken as is and compiled with clang-cl (Visual Studio 2019) gives the following: