fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. class Object
  5. {
  6. public:
  7. //...potentially lots of data...
  8. };
  9.  
  10. class ObjectHandle
  11. {
  12. public:
  13. ObjectHandle() { std::cout << "Constructed" << std::endl; }
  14. ~ObjectHandle() { std::cout << "Destructed" << std::endl; }
  15.  
  16. private:
  17. Object *ptrToPotentiallyLotsOfData = nullptr;
  18. };
  19.  
  20. int main()
  21. {
  22. std::cout << "ObjectHandle size: " << sizeof(ObjectHandle) << std::endl;
  23. std::cout << (std::is_pod<ObjectHandle>::value? "Is plain-ol`-data" : "Is not plain-old-data") << std::endl;
  24. std::cout << "\nOutter scope began" << std::endl;
  25. {
  26. std::weak_ptr<ObjectHandle> objectWPtr;
  27.  
  28. std::cout << "Inner scope began" << std::endl;
  29. {
  30. std::shared_ptr<ObjectHandle> objectSPtr = std::make_shared<ObjectHandle>();
  31. objectWPtr = objectSPtr;
  32. }
  33. std::cout << "Inner scope ended (shared_ptr goes out of scope)" << std::endl;
  34.  
  35. }
  36. std::cout << "Outter scope ended (weak_ptr goes out of scope)" << std::endl;
  37.  
  38. return 0;
  39. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
ObjectHandle size: 4
Is not plain-old-data

Outter scope began
Inner scope began
Constructed
Destructed
Inner scope ended (shared_ptr goes out of scope)
Outter scope ended (weak_ptr goes out of scope)