Advertisement
spikeysnack

onetoomany

May 20th, 2018
419
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. /* onetoomany.cpp constructs 11 items instead of 10 */
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. struct Item
  6. {
  7. public:
  8.   static size_t  ctorCount;
  9.   static size_t  dtorCount;
  10.   static size_t  cpctorCount;
  11.  
  12.   Item() { ctorCount++; }
  13.   ~Item() { dtorCount++; }
  14.   Item(const Item& item){ cpctorCount++; }
  15. };
  16.  
  17. // must initialize static memebers out of line
  18. size_t Item::ctorCount   = 0;
  19. size_t Item::dtorCount   = 0;
  20. size_t Item::cpctorCount = 0;
  21.  
  22. //creates count items in vector  
  23. void populate( std::vector<Item> & vec, int count)
  24. {
  25.   vec.reserve(count);
  26.   vec.assign(count, Item());
  27. }
  28.  
  29. int main()
  30. {
  31.  size_t count = 10;
  32.  std::vector<Item> vec;
  33.  populate( vec, count);
  34.  
  35.  std::cout << "Size of vec:\t"
  36.        << vec.size() << std::endl;
  37.  
  38.   std::cout<<"Total Item Objects constructed = "
  39.        << (Item::ctorCount + Item::cpctorCount)
  40.        << "\n";
  41.  
  42.   std::cout<<"Constructor called "
  43.        <<  Item::ctorCount << " times"
  44.        << "\n";
  45.  
  46.   std::cout<<"Copy Constructor called "
  47.        << Item::cpctorCount <<" times"
  48.        << "\n";
  49.  
  50.   std::cout<<"Total Item Objects destructed = "
  51.        <<Item::dtorCount
  52.        <<std::endl;
  53.  
  54. }
  55.  
  56. /** OUTPUT
  57.  
  58. Size of vec:    10
  59. Total Item Objects constructed = 11
  60. Constructor called 1 times
  61. Copy Constructor called 10 times
  62. Total Item Objects destructed = 1
  63.  
  64. **/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement