fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. struct A{
  5. A(int id): id(id){
  6. std::cout << id << ": constructing" << std::endl;
  7. }
  8.  
  9. ~A(){
  10. auto &s = std::cout << id << ": destroying";
  11. if (isCopy)
  12. s << " a copy";
  13. s << std::endl;
  14. }
  15.  
  16. A(const A& a) : id(a.id), isCopy(true) {
  17. std::cout << id << ": copy constructor" << std::endl;
  18. }
  19. private:
  20. int id;
  21. bool isCopy = false;
  22. };
  23.  
  24. void Copy(){
  25. std::cout << "Via copy" << std::endl;
  26. std::vector<A> v;
  27. v.reserve(3);
  28. v.push_back(A(1));
  29. v.push_back(A(2));
  30. v.push_back(A(3));
  31. }
  32.  
  33. void Move(){
  34. std::cout << std::endl;
  35. std::cout << "Via move" << std::endl;
  36. std::vector<A> v;
  37. v.reserve(3);
  38. v.emplace_back(4);
  39. v.emplace_back(5);
  40. v.emplace_back(6);
  41. }
  42.  
  43. int main(){
  44. Copy();
  45. Move();
  46. return 0;
  47. }
  48.  
Success #stdin #stdout 0s 3436KB
stdin
Standard input is empty
stdout
Via copy
1: constructing
1: copy constructor
1: destroying
2: constructing
2: copy constructor
2: destroying
3: constructing
3: copy constructor
3: destroying
1: destroying a copy
2: destroying a copy
3: destroying a copy

Via move
4: constructing
5: constructing
6: constructing
4: destroying
5: destroying
6: destroying