Search code examples
c++11moveemplace

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


I have a class A defined like bellow:

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;
   }
};

I use the class like this:

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

The emplace_back has the following output:

construct
move
copy operator

My question is, is there any way to construct A of the pair in-place without calling the move and copy operator?


Solution

  • Yes, std::pair has this constructor:

    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.

    You can therefore invoke:

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