fork download
  1. #include <cstdio> // for printf, getchar.
  2. using namespace std;
  3.  
  4. int g_count;
  5.  
  6. struct my_string
  7. {
  8. int id;
  9.  
  10. my_string()
  11. {
  12. this->id = ++g_count;
  13. printf("my_string() / [id=%d]を生成\n", this->id);
  14. }
  15.  
  16. ~my_string()
  17. {
  18. if ( this->id > 0 )
  19. printf("~my_string() / [id=%d]を破棄\n", this->id);
  20. else
  21. printf("~my_string() / 解放リソース無し\n");
  22. }
  23.  
  24. my_string(my_string const &other)
  25. {
  26. this->id = ++g_count;
  27. printf("my_string(my_string const &) / 生成[%d ← %d]\n",
  28. this->id, other.id);
  29. }
  30.  
  31. my_string(my_string &&other)
  32. {
  33. this->id = other.id;
  34. other.id = -1;
  35. printf("my_string(my_string &&) / [id=%d]を引き継ぎ\n", this->id);
  36. }
  37.  
  38. void operator=(my_string const &other)
  39. {
  40. printf("operator=(my_string const &) / [id=%d]を破棄\n", this->id);
  41. this->id = ++g_count;
  42. printf("operator=(my_string const &) / 生成[%d ← %d]\n",
  43. this->id, other.id);
  44. }
  45.  
  46. void operator=(my_string &&other)
  47. {
  48. printf("operator=(my_string &&) / [id=%d]を破棄\n", this->id);
  49. this->id = other.id;
  50. other.id = -1;
  51. printf("operator=(my_string &&) / [%d]を引き継ぎ\n", this->id);
  52. }
  53. };
  54.  
  55. my_string f()
  56. {
  57. return my_string();
  58. }
  59.  
  60. void f2(my_string &r)
  61. {
  62. r = my_string();
  63. }
  64.  
  65.  
  66. int main()
  67. {
  68. my_string i;
  69.  
  70. printf("\n----f\n");
  71. i = f(), printf(" (after return)\n");
  72.  
  73. printf("\n----f2\n");
  74. f2(i), printf(" (after return)\n");
  75. printf("\n----\n");
  76. }
  77.  
  78.  
Success #stdin #stdout 0s 2896KB
stdin
Standard input is empty
stdout
my_string() / [id=1]を生成

----f
my_string() / [id=2]を生成
operator=(my_string &&) / [id=1]を破棄
operator=(my_string &&) / [2]を引き継ぎ
 (after return)
~my_string() / 解放リソース無し

----f2
my_string() / [id=3]を生成
operator=(my_string &&) / [id=2]を破棄
operator=(my_string &&) / [3]を引き継ぎ
~my_string() / 解放リソース無し
 (after return)

----
~my_string() / [id=3]を破棄