fork(1) download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <cstring>
  4.  
  5. class String
  6. {
  7. int length_;
  8. char * data_;
  9.  
  10. public:
  11. String()
  12. : length_ { 0 }
  13. , data_ { nullptr }
  14. {
  15. }
  16.  
  17. String(char const * str, int len = 0)
  18. : length_ { static_cast<int>(len ? len : strlen(str)) }
  19. , data_ { new char[length_ + 1] }
  20. {
  21. strcpy(data_, str);
  22. }
  23.  
  24. String(String const & orig)
  25. : length_ { orig.length_ }
  26. , data_ { new char[length_ + 1] }
  27. {
  28. strcpy(data_, orig.data_);
  29. }
  30.  
  31. String & operator = (String const & orig)
  32. {
  33. String tmp { orig };
  34. swap(tmp);
  35. return *this;
  36. }
  37.  
  38. ~String()
  39. {
  40. delete[] data_;
  41. }
  42.  
  43. void swap(String & other)
  44. {
  45. if (this == &other) return;
  46. std::swap(length_, other.length_);
  47. std::swap(data_, other.data_);
  48. }
  49.  
  50. String operator + (String const & rhs) const
  51. {
  52. String result;
  53. result.length_ = length_ + rhs.length_ + 1;
  54. result.data_ = new char[result.length_];
  55. strcpy(result.data_, data_);
  56. strcat(result.data_, rhs.data_);
  57. return result;
  58. }
  59.  
  60. char const * c_str() const
  61. {
  62. return data_;
  63. }
  64. };
  65.  
  66. int main()
  67. {
  68. String foo { "foo" };
  69. String bar { "bar" };
  70. std::cout << (foo + bar).c_str() << std::endl;
  71. return 0;
  72. }
  73.  
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
foobar