String

class String {
 public:
  String() { Copy(""); }

  String(const char *cstr) {
    assert(cstr != nullptr);
    Copy(cstr);
  }

  String(const String &s) {
    if (g_debug_log) {
      printf("String(String &s) called \n");
    }

    Copy(s.cstr());
  }

  String &operator=(const String &s) {
    if (g_debug_log) {
      printf("String &operator=(const String &s) called \n");
    }

    if (this != &s) {
      delete[] cstr_;
      Copy(s.cstr());
    }
    return *this;
  }

  String(String &&s) noexcept {
    if (g_debug_log) {
      printf("String(String &&s) called \n");
    }

    cstr_ = s.cstr_;
    len_ = s.len_;
    s.cstr_ = nullptr;
    s.len_ = 0;
  }

  String &operator=(String &&s) {
    if (g_debug_log) {
      printf("String &operator=(String &&s) called \n");
    }

    if (this != &s) {
      delete[] cstr_;
      cstr_ = s.cstr_;
      len_ = s.len_;
      s.cstr_ = nullptr;
      s.len_ = 0;
    }
    return *this;
  }

  ~String() { delete[] cstr_; }

  const char *cstr() const { return cstr_; }

 private:
  char *cstr_;
  int len_;

  void Copy(const char *cstr) {
    len_ = strlen(cstr);
    cstr_ = new char[len_ + 1];
    strcpy(cstr_, cstr);  // Copy include '\0'
  }
};

inline std::ostream &operator<<(std::ostream &os, const String &s) {
  if (s.cstr() != nullptr) {
    os << s.cstr();
  } else {
    os << "nullptr";
  }
  return os;
}

results matching ""

    No results matching ""