fork download
  1. #include <iostream>
  2. #include <deque>
  3. #include <algorithm>
  4. #include <utility>
  5. #include <memory>
  6. using namespace std;
  7.  
  8. deque<bool> pool;
  9.  
  10. class ExpressionTemp;
  11. class Scalar
  12. {
  13. bool *alive;
  14.  
  15. friend class ExpressionTemp;
  16.  
  17. Scalar(const Scalar&);
  18. Scalar &operator=(const Scalar&);
  19. Scalar &operator=(Scalar&&);
  20. public:
  21. Scalar()
  22. {
  23. pool.push_back(true);
  24. alive=&pool.back();
  25. }
  26. Scalar(Scalar &&rhs)
  27. : alive(0)
  28. {
  29. swap(alive,rhs.alive);
  30. }
  31. ~Scalar()
  32. {
  33. if(alive)
  34. (*alive)=false;
  35. }
  36. };
  37. class ExpressionTemp
  38. {
  39. bool *operand_alive;
  40. public:
  41. ExpressionTemp(const Scalar &s)
  42. : operand_alive(s.alive)
  43. {
  44. }
  45. void do_job()
  46. {
  47. if(*operand_alive)
  48. cout << "captured operand is alive" << endl;
  49. else
  50. cout << "captured operand is DEAD!" << endl;
  51. }
  52. };
  53.  
  54. ExpressionTemp expression(const Scalar &s)
  55. {
  56. return {s};
  57. }
  58. int main()
  59. {
  60. {
  61. expression(Scalar()).do_job(); // OK
  62. }
  63. {
  64. Scalar lv;
  65. auto &&rvref=expression(lv);
  66. rvref.do_job(); // OK, lv is still alive
  67. }
  68. {
  69. auto &&rvref=expression(Scalar());
  70. rvref.do_job(); // referencing to dead temporary
  71. }
  72. return 0;
  73. }
  74.  
Success #stdin #stdout 0s 3020KB
stdin
Standard input is empty
stdout
captured operand is alive
captured operand is alive
captured operand is DEAD!