复制vector和赋值vector的区别是什么?

What is difference between copy and assigning a vector?

本文关键字:vector 是什么 区别 赋值 复制      更新时间:2023-10-16

复制和赋值的区别是什么?第2、4行

1    vector<int> V1(5);
2    vector<int> V3(V1);
3    vector<int> V4(V1.size());   
4    V4 = V1 ;

这是我对operator=的stl实现的氧气提取:

   /* All the elements of @a x are copied, but any extra memory in
   *  @a x (for fast expansion) will not be copied.  Unlike the
   *  copy constructor, the allocator object is not copied.
   */

正如您所看到的,如果使用自定义分配器,结果会有所不同,但在其他情况下,结果是相同的。

第2行使用了复制构造函数。第4行使用了复制赋值。两者都创建副本;第一个命令创建一个新对象,第二个命令覆盖一个现有对象。

相关文章: