为什么push_back和emplace_back结合在一起时会有不同的行为

时间:2018-08-18 16:31:08

标签: c++ c++11 vector

在以下代码中:

struct aa
{
   int a;
   aa( int x):a(x){ cout<<"const is called"<<endl;}
   ~aa(){cout <<"dest is called"<<endl;}
   aa( aa&& obj)
   {
       a = obj.a;
       cout<<"move const is called"<<endl;
   }
};
int main ()
{
  vector<aa> v1;
  v1.push_back(aa(9)); 
  v1.emplace_back(9);
}
  1. 仅使用push_back时,可以预期结果(调用Move构造函数,构造函数和析构函数。)

结果:

const is called
move const is called
dest is called
dest is called
  1. 仅使用emplace_back时,可以预期结果(不调用Move构造函数,只调用构造函数和析构函数。)

结果:

const is called
dest is called
  1. 但是当我将push_backemplace_back结合使用时,为什么要为emplace_back调用move构造函数,而在单独使用时却没有对其调用)?

结果:

const is called
move const is called
dest is called
const is called
move const is called
dest is called
dest is called
dest is called

1 个答案:

答案 0 :(得分:3)

因为同时使用push_backemplace_back,所以要向v1添加两个元素。在第二次重新分配时,将创建新的内部缓冲区,并将现有元素复制/移动到新的内部缓冲区。

您可以预先使用reserve来防止重新分配。

vector<aa> v1;
v1.reserve(2);
v1.push_back(aa(9)); 
v1.emplace_back(9);