c++ - constructor of string from char* not implicitly called? -
i have 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 following output:
,1 test,1
shouldn't 2 lines produce same output, in first case constructor string char* should implicitly called? why const reference not seem prolong life of first pair argument in first case?
it compiled gcc4.9 -std=c++11 -o3.
the problem pair pair of references, not values. when have:
using pair_t = std::pair<const std::string&, const int&>; pair_t("test",1);
the compiler needs find best candidate construction, best match in c++11 is:
template< class u1, class u2 > constexpr pair( u1&& x, u2&& y );
where types u1 = const char(&)[5]
, u2 = int
. internally, bind reference going create temporary string, when expression completes (and before returning constructor), temporary go away , left dangling reference.
the program has undefined behavior, , prints empty string in same way have crashed or print garbage.
in case do:
pair_t(std::string("test"), 1);
the expression in temporary created same expression calls function, , lifetime of temporary last until function completes, second line correct , exhibits expected behavior.
Comments
Post a Comment