22 January 2019

C++ how using reserve method in vector reduces the number of times copy constructor is called

 #include "stdafx.h"  
 #include <iostream>  
 #include <vector>  
 #include <queue>  
 #include <ctime>  
 #include <chrono>  
 #include <type_traits>  
 #include <string>  
 #include <fstream>  
 using namespace std;  
 using namespace std::chrono;  
 class Point  
 {  
 public:  
      int x; int y;  
      Point(int _x, int _y)  
      {  
           x = _x;  
           y = _y;  
           cout << "constructor " << x << ", " << y << endl;  
      }  
      ~Point()  
      {  
           cout << "destructor " << x << ", " << y <<endl;  
      }  
      Point(const Point& p)  
      {  
           x = p.x;  
           y = p.y;  
           cout << "!!! copy constructor " << x << ", " << y << endl;  
      }  
      friend std::ostream& operator<< (std::ostream& stream, const Point& p) {  
           return stream << "(" << p.x << ", " << p.y << ")";  
      }  
 };  
 Point CreatePoint()  
 {  
      Point p(100, 101);  
      return p;  
 }  
 int main()  
 {  
      vector<Point> p;  
      p.push_back(Point(1, 2));  
      p.push_back(Point(3, 4));  
      p.push_back(Point(5, 6));  
      vector<Point> p2;  
      p2.reserve(3);  
      p2.push_back(Point(10, 20));  
      p2.push_back(Point(30, 40));  
      p2.push_back(Point(50, 60));  
      Point cp = CreatePoint();  
      cout << "tesing completed." << endl;  
      getchar();  
   return 0;  
 }  
Output

constructor 1, 2
!!! copy constructor 1, 2
destructor 1, 2
constructor 3, 4
!!! copy constructor 3, 4
!!! copy constructor 1, 2
destructor 1, 2
destructor 3, 4
constructor 5, 6
!!! copy constructor 5, 6
!!! copy constructor 1, 2
!!! copy constructor 3, 4
destructor 1, 2
destructor 3, 4
destructor 5, 6
constructor 10, 20
!!! copy constructor 10, 20
destructor 10, 20
constructor 30, 40
!!! copy constructor 30, 40
destructor 30, 40
constructor 50, 60
!!! copy constructor 50, 60
destructor 50, 60
constructor 100, 101
tesing completed.
destructor 100, 101
destructor 10, 20
destructor 30, 40
destructor 50, 60
destructor 1, 2
destructor 3, 4
destructor 5, 6

No comments:

Post a Comment