fork download
  1. #include <cstdio>
  2. #include <memory>
  3.  
  4. #define KNOTE(fmt, args...) ::printf(fmt "\n", ##args)
  5. using namespace std;
  6.  
  7. class TBase
  8. {
  9. public:
  10. TBase()
  11. : IntValue(-1) {
  12. KNOTE("%s@%p: %d", __func__, this, IntValue);
  13. }
  14. virtual ~TBase() {
  15. KNOTE("%s@%p: %d", __func__, this, IntValue);
  16. }
  17. int IntValue;
  18. };
  19.  
  20. class TDerived : public TBase
  21. {
  22. public:
  23. TDerived() {
  24. IntValue = 10;
  25. KNOTE("%s@%p: %d", __func__, this, IntValue);
  26. }
  27. virtual ~TDerived() {
  28. KNOTE("%s@%p: %d", __func__, this, IntValue);
  29. }
  30. };
  31.  
  32. void TestUniquePtrCast()
  33. {
  34. std::unique_ptr<TBase> bp1(new TDerived);
  35.  
  36. // manully static cast, be careful!
  37. std::unique_ptr<TDerived> dp1(static_cast<TDerived*>(bp1.release()));
  38. // Now bp1 owns nothing
  39.  
  40. bp1 = std::move(dp1); // Now dp1 owns nothing
  41.  
  42. // manully dynamic cast, be careful!
  43. std::unique_ptr<TDerived> dp2(dynamic_cast<TDerived*>(bp1.get()));
  44. bp1.release(); // Now bp1 owns nothing
  45.  
  46. dp2->IntValue = 20;
  47. }
  48.  
  49. int main()
  50. {
  51. TestUniquePtrCast();
  52. return 0;
  53. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
TBase@0x8bcf008: -1
TDerived@0x8bcf008: 10
~TDerived@0x8bcf008: 20
~TBase@0x8bcf008: 20