fork download
  1. #include <cstdio>
  2. #include <memory>
  3.  
  4. using namespace std;
  5.  
  6. #define KNOTE(fmt, args...) ::printf(fmt "\n", ##args)
  7.  
  8. class TClass {
  9. public:
  10. TClass()
  11. : IntValue(-1) {
  12. KNOTE("%s@%p: %d", __func__, this, IntValue);
  13. }
  14. TClass(int i)
  15. : IntValue(i) {
  16. KNOTE("%s@%p: %d", __func__, this, IntValue);
  17. }
  18. ~TClass() {
  19. KNOTE("%s@%p: %d", __func__, this, IntValue);
  20. }
  21. int IntValue;
  22. };
  23.  
  24. // A function can return a shared_ptr
  25. shared_ptr<TClass> GetATClass()
  26. {
  27. auto c = std::make_shared<TClass>(0);
  28. return c;
  29. }
  30.  
  31. // A function can take a shared_ptr parameter by value
  32. // but better by const reference
  33. void DoSomething(shared_ptr<TClass> c) /* Better const shared_ptr<TClass>& */
  34. {
  35. c->IntValue = 4;
  36. }
  37.  
  38. void BasicUse()
  39. {
  40. {
  41. TClass c1; // TClass: -1
  42. std::shared_ptr<TClass> c2(new TClass(2)); // TClass: 2
  43. std::shared_ptr<TClass> c3 = std::make_shared<TClass>(3); // TClass: 3
  44. {
  45. std::shared_ptr<TClass> c4;
  46. c4.reset(new TClass(4)); // TClass: 4
  47. if (c4) {
  48. c4->IntValue = 5;
  49. }
  50. c4.reset(); // ~TClass: 5
  51. if (!c4) {
  52. KNOTE("c4 becomes null");
  53. }
  54. }
  55. c3 = GetATClass(); // c3's object is deleted and re-created
  56. // TClass: 0
  57. // ~TClass: 3
  58. DoSomething(c3); // c3->IntValue becomes 4
  59. c3.reset(); // ~TClass: 4
  60. c3 = c2; // Now c3 and c2 share ownership of TClass
  61. DoSomething(c3); // c2/c3 ->IntValue becomes 4
  62. }
  63. // c3, c2, c1 out of scope
  64. // ~TClass: 4
  65. // ~TClass: -1
  66. }
  67.  
  68. int main()
  69. {
  70. BasicUse();
  71. return 0;
  72. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
TClass@0xbff0373c: -1
TClass@0x8d3e008: 2
TClass@0x8d3e040: 3
TClass@0x8d3e048: 4
~TClass@0x8d3e048: 5
c4 becomes null
TClass@0x8d3e068: 0
~TClass@0x8d3e040: 3
~TClass@0x8d3e068: 4
~TClass@0x8d3e008: 4
~TClass@0xbff0373c: -1