在 vector::emplace_back 中就地构建 std::pair

construct std::pair in-place in vector::emplace_back

我有一个 class A 定义如下:

class A
{
public:
   A() = default;

   explicit A(uint32_t a, uint32_t b)
   {
      std::cout << "construct" << std::endl;
   }

   A(const A& obj)
   {
      std::cout << "copy" << std::endl;
      *this = obj;
   }

   A(const A&& obj)
   {
      std::cout << "move" << std::endl;
      *this = obj;
   }

   A& operator=(const A& obj)
   {
      std::cout << "copy operator" << std::endl;
      return *this;
   }

   A& operator=(const A&& obj)
   {
      std::cout << "move operator" << std::endl;
   }
};

我这样使用class:

std::vector<std::pair<A, bool>> v;
v.emplace_back(A(0, 1), true);

emplace_back 有以下输出:

construct
move
copy operator

我的问题是,有没有什么方法可以在不调用 movecopy operator 的情况下就地构造 A 对?

是的,std::pair 有这个构造函数:

cppreference/utility/pair/pair

template< class... Args1, class... Args2 >
pair( std::piecewise_construct_t,
      std::tuple<Args1...> first_args,
      std::tuple<Args2...> second_args );

Forwards the elements of first_args to the constructor of first and forwards the elements of second_args to the constructor of second. This is the only non-default constructor that can be used to create a pair of non-copyable non-movable types.

因此您可以调用:

std::vector<std::pair<A, bool>> v;
v.emplace_back(std::piecewise_construct, 
               std::make_tuple(0, 1), 
               std::make_tuple(true));