Featured image of post String

String

implementing std::string

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <string.h>

class String {
 public:
  String(char *in);
  ~String();
  String(const String &other);
  String &operator=(const String &other);
  String(String &&other);
  String &operator=(String &&other);

  friend std::ostream &operator<<(std::ostream &os, const String &str);
 private:
  char *data_;
};

String::String(char *in) {
  data_ = new char[strlen(in) + 1];
  strcpy(data_, in);
}

String::~String() {
  delete[] data_;
}

String::String(const String &other) {
  data_ = new char[strlen(other.data_) + 1];
  strcpy(data_, other.data_);
}

String &String::operator=(const String &other) {
  if (data_ != other.data_) {
    delete[] data_;
    data_ = new char[strlen(other.data_) + 1];
    strcpy(data_, other.data_);
  }
  return *this;
}

String::String(String &&other) {
  data_ = other.data_;
  other.data_ = nullptr;
}

String &String::operator=(String &&other) {
  if (data_ != other.data_) {
    delete[] data_;
    data_ = other.data_;
    other.data_ = nullptr;
  }
  return *this;
}

std::ostream &operator<<(std::ostream &os, const String &str) {
  os << str.data_;
  return os;
}

int main() {
  String s1("Vidge Is Unique!!");
  std::cout << s1 << std::endl;

  String s2 = s1;
  std::cout << s2 << std::endl;

  String s3 = std::move(s1);
  std::cout << s3 << std::endl;
}
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy