Why is std::pair from anonymous object copying that object instead of moving?

There’s a problem with how std::pair is defined. I’d even say it’s a minor defect in the standard.

It has two constructors that could be used here:

  1. pair(const T1 &x, const T2 &y);, where T1, T2 are template parameters of the pair.

  2. template <class U1, class U2> pair(U1 &&x, U2 &&y);

If you do std::pair<A, A> a{A{}, A{}});, then the second constructor is selected and all is well.

But if you do std::pair<A, A> a{{}, {}};, the compiler can’t use the second constructor because it can’t deduce U1, U2, because {} by itself has no type. So the first constructor is used and you get a copy.

For it to work properly, std::pair should have an extra non-template constructor pair(T1 &&, T2 &&), and for a good measure two extra constructors: pair(const T1 &, T2 &&) and pair(T1 &&, const T2 &).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)