So as I'm creating my own string class using smart pointers (so I can get accustomed to them), and it has mostly been going well, except for the operator+() function.
It keeps crashing the program, and when VS debugs the program, the destructor is throwing an exception. I can't seem to pinpoint why, this is the only function causing the program to crash, even when I remove all of the algorithms, and simply return a mystring object.
Any suggestions?
#include <iostream>
#include <string>
#include <memory>
#include <cstring>
using namespace std;
class mystring {
public:
mystring() : word(make_unique<char[]>('\0')), len(0) {}
~mystring() { cout << "goodbye objects!";}
mystring(const char *message) : word(make_unique<char[]>(strlen(message) + 1)), len(strlen(message)) {
for (int i = 0; i < len; i++) word[i] = message[i];
word[len] = '\0';
}
mystring(const mystring &rhs) : word(make_unique<char[]>(rhs.len)), len(rhs.len + 1) {
for (int i = 0; i < len; i++) word[i] = rhs.word[i];
word[len] = '\0';
}
mystring &operator=(const mystring &rhs) {
if (this != &rhs) {
releaseWord();
word = make_unique<char[]>(rhs.len + 1);
len = rhs.len;
for (int i = 0; i < len; i++) word[i] = rhs.word[i];
word[len] = '\0';
}
return *this;
}
//what is wrong with this function/what should be changed?
friend mystring operator+(const mystring& lhs, const mystring& rhs) {
mystring Result;
int lhsLength = lhs.len, rhsLength = rhs.len;
Result.releaseWord();
Result.word = make_unique<char[]>(lhsLength + rhsLength + 1);
Result.len = lhsLength + rhsLength;
for (int i = 0; i < lhsLength; i++) Result.word[i] = lhs.word[i];
for (int j = lhsLength; j < Result.len; j++) Result.word[j] = rhs.word[j];
Result.word[Result.len] = '\0';
return Result;
}
friend ostream &operator<<(ostream &os, const mystring &message) {
return os << message.word.get();
}
int size() const {
return len;
}
private:
int len;
unique_ptr<char[]> word;
void releaseWord() {
char *temp = word.release();
delete[] temp;
}
};
int main()
{
mystring word1 = "Darien", word2 = "Miller", word3;
cout << word1 + word2;//causes heap corruption
word3 = word1 + word2; //causes heap corruption
return 0;
}
make_unique<char[]>('\0')allocates zero bytes because'\0'is just another way of writing 0.