0

map is an std::unordered_map. T has a move constructor.

void foo(const std::string& s, T&& t) {
    map.insert(std::pair<std::string, T>(s, t));
}

T t;
foo("", std::move(t));

Why isn't this code calling template<class U, class V> std::pair(U&& a, V&& b)?


Why do we need to use std::move(t) to get the right behavior?

void foo(const std::string& s, T&& t) {
    map.insert(std::pair<std::string, T>(s, std::move(t)));
}
  • That's because `t` is an lvalue (of type `T&&`, which simply means it will match an rvalue argument, not that `t` is itself an rvalue), not an rvalue. The `std::move` is to make it an rvalue. – C. K. Young Feb 17 '16 at 21:44
  • [This article](http://thbecker.net/articles/rvalue_references/section_01.html) does a good job of explaining rvalue references – Praetorian Feb 17 '16 at 21:49
  • The code *does* call `insert(V&&v)` because the `std::pair` is a prvalue. However it does not move out of `t`. – M.M Feb 17 '16 at 22:15
  • @M.M you're right I wanted to say about pair constructor. I fixed it. – Alexis Oblet Feb 18 '16 at 08:56

0 Answers0