Advertisement
TomH22

Untitled

Apr 29th, 2020
371
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.09 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstring>
  3. #include <stdexcept>
  4. #include <utility>
  5.  
  6. struct SimpleString {
  7.   SimpleString(size_t max_size)
  8.       : max_size{ max_size }
  9.       , length{} {
  10.     if(max_size == 0) {
  11.       throw std::runtime_error{ "Max size must be at least 1." };
  12.     }
  13.     buffer = new char[max_size];
  14.     buffer[0] = 0;
  15.   }
  16.   ~SimpleString() {
  17.     delete[] buffer;
  18.   }
  19.   SimpleString(const SimpleString& other)
  20.       : max_size{ other.max_size }
  21.       , buffer{ new char[other.max_size] }
  22.       , length{ other.length } {
  23.     std::strncpy(buffer, other.buffer, max_size);
  24.   }
  25.   SimpleString(SimpleString&& other) noexcept
  26.       : max_size(other.max_size)
  27.       , buffer(other.buffer)
  28.       , length(other.length) {
  29.     other.length = 0;
  30.     other.buffer = nullptr;
  31.     other.max_size = 0;
  32.   }
  33.   SimpleString& operator=(const SimpleString& other) {
  34.     if(this == &other)
  35.       return *this;
  36.     const auto new_buffer = new char[other.max_size];
  37.     delete[] buffer;
  38.     buffer = new_buffer;
  39.     length = other.length;
  40.     max_size = other.max_size;
  41.     std::strncpy(buffer, other.buffer, max_size);
  42.     return *this;
  43.   }
  44.   SimpleString& operator=(SimpleString&& other) noexcept {
  45.       if (this == &other)
  46.           return *this;
  47.       delete[] buffer;
  48.       max_size = other.max_size;
  49.       buffer = other.buffer;
  50.       length = other.length;
  51.  
  52.       max_size = 0;
  53.       buffer = nullptr;
  54.       length = 0;
  55.       return *this;
  56.   }
  57.   void print(const char* tag) const {
  58.     printf("%s: %s", tag, buffer);
  59.   }
  60.   bool append_line(const char* x) {
  61.     const auto x_len = strlen(x);
  62.     if(x_len + length + 2 > max_size)
  63.       return false;
  64.     std::strncpy(buffer + length, x, max_size - length);
  65.     length += x_len;
  66.     buffer[length++] = '\n';
  67.     buffer[length] = 0;
  68.     return true;
  69.   }
  70.  
  71.   private:
  72.   size_t max_size;
  73.   char* buffer;
  74.   size_t length;
  75. };
  76.  
  77. int main() {
  78.   SimpleString a{ 50 };
  79.   a.append_line("We apologise for the");
  80.   SimpleString b{ 50 };
  81.   b.append_line("Last message");
  82.   a.print("a");
  83.   b.print("b");
  84.   b = std::move(a);
  85.   // a is "moved-from"
  86.   b.print("b");
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement