当存在完美的转发构造函数时,左右引用构造函数的意图是什么?

时间:2018-01-04 09:16:46

标签: c++ constructor move-semantics rvalue-reference perfect-forwarding

我们以std::pair<T1, T2>为例。它有以下两个构造函数:

constexpr pair( const T1& x, const T2& y );                      // #1
template< class U1, class U2 > constexpr pair( U1&& x, U2&& y ); // #2

似乎#2可以处理#1可以处理的所有情况(没有更差的性能),除了参数是list-initializer的情况。例如,

std::pair<int, int> p({0}, {0}); // ill-formed without #1

所以我的问题是:

  • 如果#1仅用于list-initializer参数,由于xy最终绑定到从list-initializers初始化的临时对象,为什么不使用constexpr pair( T1&& x, T2&& y );代替?

  • 否则,#1的实际意图是什么?

2 个答案:

答案 0 :(得分:3)

如果您要存储的对象是临时对象但不可移动,该怎么办?

#include <type_traits>
#include <utility>
#include <iostream>

class   test
{
public:
  test() { std::cout << "ctor" << std::endl; }
  test(const test&) { std::cout << "copy ctor" << std::endl; }
  test(test&&) = delete; // { std::cout << "move ctor" << std::endl; }
  ~test() { std::cout << "dtor" << std::endl; }

private:
  int dummy;
};

template <class T1, class T2>
class   my_pair
{
public:
  my_pair() {}
  // Uncomment me plz !
  //my_pair(const T1& x, const T2& y) : first(x), second(y) {}
  template <class U1, class U2, class = typename std::enable_if<std::is_convertible<U1, T1>::value && std::is_convertible<U2, T2>::value>::type>
  my_pair(U1&& x, U2&& y) : first(std::forward<U1>(x)), second(std::forward<U2>(y)) {}

public:
  T1 first;
  T2 second;
};

int     main()
{
  my_pair<int, test>    tmp(5, test());
}

上面的代码无法编译,因为my_pair所谓的“完美”转发构造函数将临时test对象转发为右值引用,后者又尝试调用显式删除的移动构造函数test

如果我们从my_pair删除注释不是那么“完美”的构造函数,那么它最好通过重载解析来强制执行临时test对象的副本,从而使其工作。

答案 1 :(得分:1)

你回答了自己的问题。

pair( const T1& x, const T2& y ); 之前在C ++ 17中添加了转发构造函数。 {C} 14中添加了constexpr。现在为什么要保持构造函数?有两个原因:1)向后兼容性和2)因为如你所说,完美格式化的代码会拒绝编译。 C ++非常强调向后兼容性,并采用非常保守的方法来弃用代码,因为它可能以意想不到的方式中断。

现在,如果您想要更实际的示例,请尝试std::for_each。您可以将其更改为完美转发仿函数而不会破坏代码。但是,添加此更改的动机很小,因为它指定只生成一个副本。换句话说,改变的优先级不是很高。