fork(6) download
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. class mystr {
  5. private:
  6. char *str;
  7. size_t len, buflen;
  8. int *refcount;
  9.  
  10. public:
  11. const char *c_str() const { return str; }
  12. size_t length() const { return len; }
  13.  
  14. mystr() {
  15. str = NULL;
  16. *this = "";
  17. }
  18.  
  19. mystr(const char *s) {
  20. str = NULL;
  21. *this = s;
  22. }
  23.  
  24. mystr(const mystr &s) {
  25. str = NULL;
  26. *this = s;
  27. }
  28.  
  29. ~mystr() {
  30. unset(str);
  31. }
  32.  
  33. void printn() const {
  34. printf("%s\n", str);
  35. }
  36.  
  37. private:
  38. void set(const char *s, size_t newlen) {
  39. char *old = str;
  40. len = newlen;
  41. if (!old || buflen < len) {
  42. if (!old) buflen = 16;
  43. while (buflen < len)
  44. buflen += buflen;
  45. str = new char[buflen + 1];
  46. } else if (*refcount > 1) {
  47. str = new char[buflen + 1];
  48. }
  49. if (str != s) strcpy(str, s);
  50. if (old != str) {
  51. unset(old);
  52. refcount = new int(1);
  53. }
  54. }
  55.  
  56. void unset(char *str) {
  57. if (str && --*refcount == 0) {
  58. delete refcount;
  59. delete[] str;
  60. }
  61. }
  62.  
  63. public:
  64. mystr &operator+=(const char *s) {
  65. int oldlen = len;
  66. set(str, len + strlen(s));
  67. strcpy(&str[oldlen], s);
  68. return *this;
  69. }
  70.  
  71. mystr &operator+=(const mystr &s) {
  72. int oldlen = len;
  73. set(str, len + s.len);
  74. strcpy(&str[oldlen], s.str);
  75. return *this;
  76. }
  77.  
  78. mystr &operator=(const char *s) {
  79. set(s, strlen(s));
  80. return *this;
  81. }
  82.  
  83. mystr &operator=(const mystr &s) {
  84. unset(str);
  85. str = s.str;
  86. len = s.len;
  87. buflen = s.buflen;
  88. ++*(refcount = s.refcount);
  89. return *this;
  90. }
  91.  
  92. mystr substr(int start, int len) const {
  93. mystr ret;
  94. ret.set("", len);
  95. strncpy(ret.str, &str[start], len);
  96. ret.str[len] = 0;
  97. return ret;
  98. }
  99. };
  100.  
  101. mystr operator+(const mystr &s1, const mystr &s2) {
  102. mystr ret = s1;
  103. ret += s2;
  104. return ret;
  105. }
  106.  
  107. int main() {
  108. mystr s1 = "abc", s2 = s1;
  109. s1 += "def";
  110. printf("s1[%d]%s\n", s1.length(), s1.c_str());
  111. printf("s2[%d]%s\n", s2.length(), s2.c_str());
  112. }
  113.  
Success #stdin #stdout 0s 2816KB
stdin
Standard input is empty
stdout
s1[6]abcdef
s2[3]abc