So I was learning OOP in C++ and I thought it would be a good practice to write my own string class (for learning purposes, of course). I came up with a problem which I didn't know how to solve. Here's some peace of code:
class String {
char *str;
public:
String(char const *str);
~String();
String operator + (char const *str);
};
String::String(char *str) {
this->str = _strdup(str);
}
String::~String() {
free(this->str);
}
String String::operator+(char const *str) {
char *temp = (char *) malloc(strlen(str) + strlen(this->str) + 1);
strcpy(temp, this->str);
strcat(temp, str);
return temp;
}
The problem here is, that this piece of code will cause a memory leak. Return from "operator +" invokes my constructor, which copies temp by allocating more memory and I couldn't find any way how can I free it.