dimanche 28 décembre 2014

vector memory allocation call to copy constructor with push_back function


#include <vector>
#include <iostream>
#include <iterator>

using namespace std;

class MoveableClass
{
public:
MoveableClass() {
cout << "Default constructor" << endl;
}
MoveableClass(const MoveableClass& src) {
cout << "Copy constructor" << endl;
}
MoveableClass(MoveableClass&& src) {
cout << "Move constructor" << endl;
}
MoveableClass& operator=(const MoveableClass& rhs) {
cout << "Copy assignment operator" << endl;
return *this;
}
MoveableClass& operator=(MoveableClass&& rhs) {
cout << "Move assignment operator" << endl;
return *this;
}
};

int main()
{
vector<MoveableClass> vecSource(3);
cout << "----" << endl;
MoveableClass mc;
cout << "----" << endl;
vecSource.push_back(mc);
// vecSource.push_back(mc);
// vecSource.push_back(mc);
// vecSource.push_back(mc);
cout << "----" << endl;
// Copy the elements from vecSource to vecOne
vector<MoveableClass> vecOne(vecSource.begin(), vecSource.end());
cout << "----" << endl;
// Move the elements from vecSource to vecTwo
vector<MoveableClass> vecTwo(make_move_iterator(vecSource.begin()),
make_move_iterator(vecSource.end()));
cout << "----" << endl;

return 0;
}


From the above code I have 2 doubts:




  1. Why move ctor is not called from implemented class when I use 2 push_back(mc) functions call to copy ctor is 3 times i.e 1 for first push and for 2nd push first vector is resized (sequently grow) to different memory location (which should have triggered move for first push) 3rd for 2nd push




  2. Even when I initialize the vector object with size 3 why the call to copy ctor increases to 4 for one push_back(mc).




Output:



Default constructor
Default constructor
Default constructor
----
Default constructor
----
Copy constructor
Copy constructor
Copy constructor
Copy constructor
----
Copy constructor
Copy constructor
Copy constructor
Copy constructor
----
Move constructor
Move constructor
Move constructor
Move constructor
----


gcc version I am using is:



gcc version 4.7.3



Aucun commentaire:

Enregistrer un commentaire