c++11 - 在 vector::emplace_back 中就地构造 std::pair

标签 c++11 move 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;
   }
};

我这样使用类:

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

emplace_back 具有以下输出:

construct
move
copy operator

我的问题是,有没有什么方法可以在不调用 move 复制运算符的情况下就地构建对的 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));

关于c++11 - 在 vector::emplace_back 中就地构造 std::pair,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55831362/

相关文章:

c++ - 无法从初始化列表中的 lambda 中推断出类型

c++11 - 如何使用 c++11 为旧 Linux 版本构建二进制文件?

C++11:用于调用类型的默认构造函数的可变参数 lambda 模板

boost - 在 C++11 中的 boost::asio 套接字对象上重复 std::move

c++11 - 安置在D

C++11:将 POD 附加到 vector<> 的最有效方法

c++ - Mersenne Twister 种子作为成员变量

css - 将鼠标移到社交图标上时如何更改它们的颜色?

c++11 - 连续存储容器和 move 语义