I started learning C++ about a week ago and I was hoping somebody can critique my code. I decided to implement my own basic String class just for the sake of applying all that I've learned about pointers, C-style strings, and move semantics. I know there is already such a class in the standard library but as I said, I only did this to apply what I currently know.
Anyhow, here is the string_re.h
header file:
#pragma once
class String {
private:
char* m_Buffer;
int m_Size;
public:
String();
String(const char*);
String(String&);
~String();
String& operator=(String&);
String& operator=(String&&);
String& operator+=(const String&);
String operator+(const String&);
friend String operator+(const char*, const String&);
friend int len(String&);
void print();
};
String operator+(const char*, const String&);
int len(const char*);
int len(String&);
void copy(char*, const char*, int);
And here is the string_re.cpp
implementation file:
#include <cstdio>
#include "string_re.h"
String::String() {
m_Buffer = nullptr;
m_Size = 0;
}
String::String(const char* c) {
m_Size = len(c);
m_Buffer = new char[m_Size + 1];
copy(m_Buffer, c, 0);
}
String::String(String& s) {
m_Size = s.m_Size;
m_Buffer = new char[m_Size + 1];
copy(m_Buffer, s.m_Buffer, 0);
}
String::~String() {
delete[] m_Buffer;
}
String& String::operator=(String& s) {
delete[] m_Buffer;
m_Size = s.m_Size;
m_Buffer = new char[m_Size + 1];
copy(m_Buffer, s.m_Buffer, 0);
return *this;
}
String& String::operator=(String&& s) {
delete[] m_Buffer;
m_Size = s.m_Size;
m_Buffer = s.m_Buffer;
s.m_Size = 0;
s.m_Buffer = nullptr;
return *this;
}
String& String::operator+=(const String& s) {
int size = m_Size + s.m_Size;
char* new_buffer = new char[size + 1];
copy(new_buffer, m_Buffer, 0);
copy(new_buffer, s.m_Buffer, m_Size);
delete[] m_Buffer;
m_Buffer = new_buffer;
m_Size = size;
return *this;
}
String String::operator+(const String& s) {
String tmp(*this);
tmp += s;
return tmp;
}
String operator+(const char* c, const String& s) {
String tmp(c);
tmp += s;
return tmp;
}
void String::print() {
printf("%s\n", m_Buffer);
}
int len(const char* c) {
int size = 0;
while (c[size] != '\0') size++;
return size;
}
int len(String& s) {
return s.m_Size;
}
void copy(char* c1, const char* c2, int start) {
if (c2 == nullptr) return;
while (*c2 != '\0') c1[start++] = *c2++;
c1[start] = *c2;
}
Yes, I know there is already a memcpy
and a strlen
function but I decided to implement my own anyways. All my String class does is concatenate other Strings and nothing more. Also, I feel like there's a better way to implement the + operator function but I just can't wrap my head around it. Any feedback would be much appreciated!