在向量:: emplace_back中就地构造std :: pair

Cri*_*ket 2 move c++11 emplace

我有一个像下面这样定义的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;
   }
};
Run Code Online (Sandbox Code Playgroud)

我使用这样的类:

std::vector<std::pair<A, bool>> v;
v.emplace_back(A(0, 1), true);
Run Code Online (Sandbox Code Playgroud)

emplace_back具有以下输出:

construct
move
copy operator
Run Code Online (Sandbox Code Playgroud)

我的问题是,有没有办法在不调用move and copy运算符的情况下就地构造该对的A ?

Vit*_*meo 5

是的,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 );
Run Code Online (Sandbox Code Playgroud)

的前方的元素first_args到的构造firs吨和转发该元件second_args到的构造second。这是唯一可用于创建一对不可复制的不可移动类型的非默认构造函数。

因此,您可以调用:

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