fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <sstream>
  4. #include <vector>
  5. #include <string>
  6. #include <memory>
  7. #include <map>
  8. #include <set>
  9.  
  10. class HasPtr
  11. {
  12. public:
  13. HasPtr(std::string const &s = std::string())
  14. : ptr(new std::string(s)), use(new std::size_t(1)) {}
  15. HasPtr(const HasPtr &p)
  16. : ptr(p.ptr), use(p.use)
  17. {
  18. ++*use;
  19. std::cout << "copy constructor" << std::endl;
  20. }
  21. ~HasPtr()
  22. {
  23. if (--*use == 0)
  24. {
  25. delete ptr;
  26. delete use;
  27. }
  28. }
  29. HasPtr& operator=(const HasPtr &rhs)
  30. {
  31. //++*rhs.use;
  32. if (--*use)
  33. {
  34. delete ptr;
  35. delete use;
  36. }
  37. ++*rhs.use;
  38. ptr = rhs.ptr;
  39. use = rhs.use;
  40.  
  41. std::cout << "operaator=" << std::endl;
  42.  
  43. return *this;
  44. }
  45. private:
  46. std::string *ptr;
  47. std::size_t *use;
  48. };
  49.  
  50. void f(HasPtr x) {}
  51.  
  52. int main()
  53. {
  54. HasPtr h(std::string("xxx"));
  55. h = h;
  56. f(h);
  57. return 0;
  58. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
operaator=
copy constructor