[英]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);
}
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
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
push_back
with emplace_back
, why move constructor is called for emplace_back
while it was not called when used separately) ? push_back
与emplace_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_back
和emplace_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.