fork download
  1. #include <string>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. struct Song
  6. {
  7. Song( const std::string& name, const std::string& by )
  8. : title(name), artiste(by) { std::cout << "Song::two arg constructor\n" ; }
  9.  
  10. Song( const Song& that ) : title(that.title), artiste(that.artiste)
  11. { std::cout << "Song::copy constructor\n" ; }
  12.  
  13. const std::string title ;
  14. const std::string artiste ;
  15. };
  16.  
  17. int main()
  18. {
  19. std::vector<Song> favourites ; // empty sequence
  20. favourites.reserve(5) ; // reserve space for upto 5 songs
  21.  
  22. Song autumn( "Autumn in New York", "Billie Holiday" ) ; // Song::two arg constructor
  23. favourites.push_back(autumn) ; // vector makes a copy: Song::copy constructor
  24.  
  25.  
  26. std::cout << '\n' ;
  27. // 1. construct an anonymous song object and pass that to push_back()
  28. // 2. the vector makes a copy
  29. favourites.push_back( Song( "Summertime", "Sarah Vaughan" ) ) ;
  30. // Song::two arg constructor
  31. // Song::copy constructor
  32.  
  33.  
  34. std::cout << '\n' ;
  35. // construct a song object in situ inside the vector (avoids the extra copy)
  36. favourites.emplace_back( "It Might as Well Be Spring", "Astrud Gilberto" ) ;
  37. // Song::two arg constructor
  38.  
  39.  
  40. std::cout << '\n' ;
  41. // allocate memory for a new buffer which can hold upto 50 songs
  42. // copy the three songs into the new buffer
  43. favourites.reserve(50) ; // reserve space for upto 5 songs
  44. // Song::copy constructor
  45. // Song::copy constructor
  46. // Song::copy constructor
  47. }
  48.  
Success #stdin #stdout 0s 3436KB
stdin
Standard input is empty
stdout
Song::two arg constructor
Song::copy constructor

Song::two arg constructor
Song::copy constructor

Song::two arg constructor

Song::copy constructor
Song::copy constructor
Song::copy constructor