fork(1) 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 &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. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp:13:38: error: invalid initialization of non-const reference of type 'std::string& {aka std::basic_string<char>&}' from an rvalue of type 'std::string {aka std::basic_string<char>}'
  HasPtr(std::string &s = std::string())
                                      ^
prog.cpp: In function 'int main()':
prog.cpp:54:29: error: invalid initialization of non-const reference of type 'std::string& {aka std::basic_string<char>&}' from an rvalue of type 'std::string {aka std::basic_string<char>}'
  HasPtr h(std::string("xxx"));
                             ^
prog.cpp:13:2: note:   initializing argument 1 of 'HasPtr::HasPtr(std::string&)'
  HasPtr(std::string &s = std::string())
  ^
stdout
Standard output is empty