Advertisement
andrejpodzimek

operator +=

Jan 20th, 2023 (edited)
735
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <memory>
  4. #include <string_view>
  5. #include <utility>
  6.  
  7. namespace {
  8. struct StringF {
  9.  public:
  10.   StringF() : StringF{0} {}
  11.   StringF(std::string_view from) : StringF{from.size()} {
  12.     std::copy(from.begin(), from.end(), begin());
  13.   }
  14.   char* begin() const { return &string_[0]; }
  15.   char* end() const { return &string_[size_]; }
  16.  
  17.   StringF& operator+=(const StringF& right) {
  18.     StringF concat{size_ + right.size_};
  19.     std::copy(begin(), end(), concat.begin());
  20.     std::copy(right.begin(), right.end(), concat.begin() + size_);
  21.     std::swap(string_, concat.string_);  // `concat` frees old `string_`
  22.     std::swap(size_, concat.size_);
  23.     return *this;
  24.   }
  25.  
  26.  private:
  27.   StringF(size_t size)
  28.       : size_{size}, string_{std::make_unique<char[]>(size_ + 1)} {
  29.     string_[size_] = '\0';
  30.   }
  31.  
  32.   size_t size_;
  33.   std::unique_ptr<char[]> string_;
  34. };
  35.  
  36. std::ostream& operator<<(std::ostream& out, const StringF& in) {
  37.   return out << in.begin();
  38. }
  39. }  // namespace
  40.  
  41. int main() {
  42.   const StringF empty;
  43.   const StringF space{" "};
  44.   const StringF boo{"boo"};
  45.   const StringF foo{"foo"};
  46.   std::cout << empty << boo << space << foo << '\n';  // boo foo
  47.  
  48.   StringF acc;
  49.   acc += boo;
  50.   acc += empty;
  51.   acc += boo;
  52.   std::cout << acc << '\n';  // booboo
  53.   acc += space;
  54.   acc += foo;
  55.   acc += empty;
  56.   acc += foo;
  57.   std::cout << acc << '\n';  // booboo foofoo
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement