#include "String.h" #include #include #include namespace ecci { #ifdef TESTING /*static*/ size_t String::instanceCount = 0; #endif String::String(const char* cstring) : length{ Length(strlen(cstring)) } , text{ new char[ length + 1 ] } { assert(text); strcpy(text, cstring); #ifdef TESTING ++instanceCount; #endif #ifdef TESTING2 instanceNumber = instanceCount; std::cerr << "String(" << text << ")[" << instanceNumber << "]\n"; #endif } String::String(Length capacity) : length(0) , text(new char[capacity + 1]) { text[0] = '\0'; #ifdef TESTING ++instanceCount; #endif #ifdef TESTING2 instanceNumber = instanceCount; std::cerr << "String[" << capacity << "][" << instanceNumber << "]\n"; #endif } String::String(const String& other) : length{ other.length } , text{ new char[ length + 1 ] } { assert(text); strcpy(text, other.text); #ifdef TESTING ++instanceCount; #endif #ifdef TESTING2 instanceNumber = instanceCount; std::cerr << "StringCp(" << text << ")[" << instanceNumber << "]\n"; #endif } String::String(String&& other) : length{ other.length } , text{ other.text } { other.length = 0; other.text = nullptr; #ifdef TESTING ++instanceCount; #endif #ifdef TESTING2 instanceNumber = instanceCount; std::cerr << "StringMv(" << text << ")[" << instanceNumber << "]\n"; #endif } String::~String() { #ifdef TESTING --instanceCount; #endif #ifdef TESTING2 std::cerr << "~String(" << (text ? text : "nullptr") << ")[" << instanceNumber << "]\n"; #endif delete [] text; } String& String::operator=(const String& other) { if ( this != &other ) { length = other.length; delete [] text; text = new char[ length + 1 ]; assert(text); strcpy(text, other.text); } #ifdef TESTING2 std::cerr << "operator=Cp(" << text << ")[" << instanceNumber << "]\n"; #endif return *this; } String& String::operator=(String&& other) { if ( this != &other ) { length = other.length; delete [] text; text = other.text; assert(text); other.length = 0; other.text = nullptr; } #ifdef TESTING2 std::cerr << "operator=Mv(" << text << ")[" << instanceNumber << "]\n"; #endif return *this; } String String::operator+(const String& other) const { String result(this->length + other.length); strcpy(result.text, this->text); strcpy(result.text + this->length, other.text); result.length = this->length + other.length; return result; } String String::operator+(char ch) const { if ( ch == '\0') return *this; String result(this->length + 1); strcpy(result.text, this->text); result.text[this->length] = ch; result.text[this->length + 1] = '\0'; result.length = this->length + 1; return result; } /*friend*/ String operator+(char ch, const String& string) { if ( ch == '\0') return String(); String result(1 + string.length); result.text[0] = ch; strcpy(result.text + 1, string.text); result.length = 1 + string.length; return result; } } // namespace ecci