smrtptrs.cpp 757 B

1234567891011121314151617181920212223242526272829303132
  1. // smrtptrs.cpp -- using three kinds of smart pointers
  2. #include <iostream>
  3. #include <string>
  4. #include <memory>
  5. class Report
  6. {
  7. private:
  8. std::string str;
  9. public:
  10. Report(const std::string s) : str(s) { std::cout << "Object created!\n"; }
  11. ~Report() { std::cout << "Object deleted!\n"; }
  12. void comment() const { std::cout << str << "\n"; }
  13. };
  14. int main()
  15. {
  16. {
  17. std::auto_ptr<Report> ps (new Report("using auto_ptr"));
  18. ps->comment(); // use -> to invoke a member function
  19. }
  20. {
  21. std::shared_ptr<Report> ps (new Report("using shared_ptr"));
  22. ps->comment();
  23. }
  24. {
  25. std::unique_ptr<Report> ps (new Report("using unique_ptr"));
  26. ps->comment();
  27. }
  28. // std::cin.get();
  29. return 0;
  30. }