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.  
  25. // A function can return a unique_ptr by std::move
  26. // Note that return value of a function is a rvalue
  27. static std::unique_ptr<TClass> GetATClass()
  28. {
  29. std::unique_ptr<TClass> c(new TClass(0));
  30. return c; // same as `return std::move(c);`
  31. }
  32.  
  33. // A function can take a unique_ptr parameter by reference
  34. // but better by const reference
  35. void DoSomething(std::unique_ptr<TClass>& c)
  36. {
  37. c->IntValue = 4;
  38. }
  39.  
  40. void TestUniquePtrBasicUse()
  41. {
  42. {
  43. TClass c1; // TClass: -1
  44. std::unique_ptr<TClass> c2(new TClass(2)); // TClass: 2
  45. //std::unique_ptr<TClass> c3(c2); // error: use of deleted function
  46. // unique_ptr(const std::unique_ptr&)
  47.  
  48. std::unique_ptr<TClass> c3; // Empty unique_ptr
  49.  
  50. //c3 = c2; // error: use of deleted function operator=()
  51. c3 = std::move(c2); // unique_ptr has to be moved
  52. // Now c2 owns nothing
  53.  
  54. c3 = GetATClass(); // TClass: 0
  55. // ~TClass: 2
  56.  
  57. DoSomething(c3); // c3->IntValue becomes 4
  58. }
  59. // ~TClass: 4
  60. // ~TClass: -1
  61. }
  62.  
  63. int main()
  64. {
  65. TestUniquePtrBasicUse();
  66. return 0;
  67. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
TClass@0xbfbf853c: -1
TClass@0x9472008: 2
TClass@0x9472018: 0
~TClass@0x9472008: 2
~TClass@0x9472018: 4
~TClass@0xbfbf853c: -1