I have the following code.
void print_pair(const std::pair<const std::string&, const int&>& p)
{
std::cout << p.first << "," << p.second << std::endl;
}
print_pair(std::pair<const std::string&, const int&>("test",1));//1
print_pair(std::pair<const std::string&, const int&>(std::string("test"),1));//2
which produces the following output:
,1
test,1
shouldn't the two lines produce the same output, as in the first case the constructor for string from char* should be implicitly called? why does const reference not seem to prolong the life of first pair argument in the first case?
it is compiled with gcc4.9 -std=c++11 -O3.
&fromstd::string...std::pair<std::string const&, int const&>(std::string const &, int const &). Up until C++11, the temporary string would be created by the caller and it would outlive the function call. If you rerun that code in C++11 or C++14 mode you will get undefined behavior.