vector赋值发生了什么?

测试代码

#include <iostream>
#include <vector>
class A {
 public:
  A() {
    a_ = 0;
    std::cout << "constructor is called" << std::endl;
  }

  A(int a) {
    a_ = a;
    std::cout << "param constructor is called" << std::endl;
  }

  A(const A& a) {
    a_ = a.a_;
    std::cout << "copy constructor is called" << std::endl;
  }

  class A& operator=(const A& a) {
      a_ = a.a_;
      std::cout<<"operator ="<<std::endl;
  }

  ~A() { std::cout << "destructor is called" << std::endl; }

  int a_;
};

int main() {
  // if v1.size() > v2.capacity()
  {
    std::cout << "v1.size() > v2.capacity()" << std::endl;
    std::vector<A> v1;
    v1.reserve(2);
    std::vector<A> v2;
    v1.emplace_back();
    v1.emplace_back();
    v2.emplace_back();
    v2 = v1;
    std::cout << "#####" << std::endl<<std::endl;
  }
  std::cout << "#####" << std::endl<<std::endl;

  // else if v1.size() > v2.size()
  {
    std::cout << "v1.size() > v2.size()" << std::endl;
    std::vector<A> v1;
    std::vector<A> v2;
    v1.reserve(2);
    v2.reserve(3);
    v2.emplace_back();
    v1.emplace_back();
    v1.emplace_back();
    v2 = v1;
    std::cout << "#####" << std::endl<<std::endl;
  }
  std::cout << "#####" << std::endl<<std::endl;

  // else
  {
    std::cout << "v1.size() <= v2.size()" << std::endl;
    std::vector<A> v1;
    std::vector<A> v2;
    v1.emplace_back();
    v2.reserve(2);
    v2.emplace_back();
    v2.emplace_back();
    v2 = v1;
    std::cout << "#####" << std::endl<<std::endl;
  }
  std::cout << "#####" << std::endl<<std::endl;

  return 0;
}

测试结果

v1.size() > v2.capacity()
constructor is called
constructor is called
constructor is called
copy constructor is called
copy constructor is called
destructor is called
#####

destructor is called
destructor is called
destructor is called
destructor is called
#####

v1.size() > v2.size()
constructor is called
constructor is called
constructor is called
operator =
copy constructor is called
#####

destructor is called
destructor is called
destructor is called
destructor is called
#####

v1.size() <= v2.size()
constructor is called
constructor is called
constructor is called
operator =
destructor is called
#####

destructor is called
destructor is called
#####

结论

  • 如果v1.size() > v2.capacity(),会在一块新的内存执行拷贝构造函数生成一个新的vector,然后把v2的内存析构了,然后再令v2等于新生成的vector。
  • 如果v2.capacity() > v1.size() 且v1.size() > v2.size(),这时候在原来的内存进行操作。先执行v2.size()个赋值操作,然后再执行v1.size()-v2.size()个拷贝构造函数。
  • 如果v2.capacity() > v1.size() 且v1.size() <= v2.size(),这个时候也在原来的内存进行操作。先执行v1.size()个赋值操作,然后再执行v2.size()-v1.size()个析构函数。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值