在以下代码中:
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
时,可以预期结果(调用Move构造函数,构造函数和析构函数。)结果:
const is called
move const is called
dest is called
dest is called
emplace_back
时,可以预期结果(不调用Move构造函数,只调用构造函数和析构函数。)结果:
const is called
dest is called
push_back
与emplace_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
答案 0 :(得分:3)
因为同时使用push_back
和emplace_back
,所以要向v1
添加两个元素。在第二次重新分配时,将创建新的内部缓冲区,并将现有元素复制/移动到新的内部缓冲区。
您可以预先使用reserve
来防止重新分配。
vector<aa> v1;
v1.reserve(2);
v1.push_back(aa(9));
v1.emplace_back(9);