1

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 .)

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 .)

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) ?

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
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Alok
  • 1,997
  • 2
  • 18
  • 30
  • I reopened the question becaus I think the point here is not the difference between `push_back` and `emplace_back`, but why use them together leads to unexpected result. – songyuanyao Aug 18 '18 at 16:41

1 Answers1

3

Because when you use both push_back and emplace_back, you're adding two elements to 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.

vector<aa> v1;
v1.reserve(2);
v1.push_back(aa(9)); 
v1.emplace_back(9);
songyuanyao
  • 169,198
  • 16
  • 310
  • 405