简体   繁体   English

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

[英]why push_back and emplace_back when combined together, have different behaviour

In the following code: 在以下代码中:

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. when only push_back is used, result are expected ( Move constructor , constructor and destructor are called .) 当只使用push_back时,结果是预期的(调用Move构造函数,构造函数和析构函数。)

Results: 结果:

const is called
move const is called
dest is called
dest is called
  1. When only emplace_back is used , result are expected ( No Move constructor is called , only constructor and destructor are called .) 当只使用emplace_back ,结果是预期的(调用No Move构造函数,只调用构造函数和析构函数。)

Results: 结果:

const is called
dest is called
  1. but when I combined push_back with emplace_back , why move constructor is called for emplace_back while it was not called when used separately) ? 但是当我将push_backemplace_back结合使用emplace_back ,为什么移动构造函数被调用为emplace_back而单独使用emplace_back没有调用它?

Results: 结果:

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

Because when you use both push_back and emplace_back , you're adding two elements to v1 . 因为当你同时使用push_backemplace_back ,你要向v1添加两个元素。 At the 2nd time reallocation happened, new inner buffer is created and existing elements are copied/moved to new inner buffer. 在第二次重新分配时,会创建新的内部缓冲区并将现有元素复制/移动到新的内部缓冲区。

You can use reserve in advance to prevent reallocation. 您可以提前使用reserve以防止重新分配。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM