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 TPerfectCtor : public std::enable_shared_from_this<TPerfectCtor>
  9. {
  10. private:
  11. TPerfectCtor(int i = -1)
  12. : IntValue(i) {
  13. KNOTE("%s@%p: %d", __func__, this, IntValue);
  14. }
  15. TPerfectCtor(const TPerfectCtor& r) = default;
  16.  
  17. public:
  18. template<typename ... T>
  19. static std::shared_ptr<TPerfectCtor> Create(T&& ... all) {
  20. return std::shared_ptr<TPerfectCtor>(new TPerfectCtor(std::forward<T>(all)...));
  21. }
  22.  
  23. ~TPerfectCtor() {
  24. KNOTE("%s@%p: %d", __func__, this, IntValue);
  25. }
  26. std::shared_ptr<TPerfectCtor> GetItRight() {
  27. return shared_from_this();
  28. }
  29. int IntValue;
  30. };
  31.  
  32. void TestSharedFromThisPerfectCtor()
  33. {
  34. // std::shared_ptr<TPerfectCtor> c1(new TPerfectCtor()); // compile error
  35. std::shared_ptr<TPerfectCtor> c1 = TPerfectCtor::Create(); // TPerfectCtor: -1
  36. std::shared_ptr<TPerfectCtor> c2 = TPerfectCtor::Create(2); // TPerfectCtor: 2
  37. c2 = c1->GetItRight(); // ~TPerfectCtor: 2
  38. KNOTE("c1 use count: %lu", c1.use_count()); // 2
  39. KNOTE("c2 use count: %lu", c2.use_count()); // 2
  40. }
  41. // ~TPerfectCtor: -1
  42.  
  43. int main()
  44. {
  45. TestSharedFromThisPerfectCtor();
  46. return 0;
  47. }
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
TPerfectCtor@0x870e008: -1
TPerfectCtor@0x870e030: 2
~TPerfectCtor@0x870e030: 2
c1 use count: 2
c2 use count: 2
~TPerfectCtor@0x870e008: -1