I write my own class of string called MyString. In main function I first declare som string and then want to assign a new string to it.
int main()
{
MyString mystr1(3,'a');
mystr1 = "hrl";
return 0;
}
The class looks like that:
class MyString
{
public:
//default constructor, create an empty string
MyString()
{
};
//create a string containing n copies of c
MyString(size_t n, char c) :data(new char[n+1]), data_length(n)
{
for (size_t i = 0; i < n; i++)
{
data[i] = c;
}
data[n]='\0';
};
//create a string from a null-terminated array
MyString(const char *cp):data(new char[std::strlen(cp)+1]), data_length(std::strlen(cp))
{
std::copy(cp, cp + std::strlen(cp), stdext::checked_array_iterator<char*>(data, data_length));
data[data_length] = '\0';
}
//index operator for writing access
char& operator[](size_t i)
{
return data[i];
}
//index operator for read-only access
const char& operator[](size_t i) const{ return data[i];}
size_t size() const { return data_length; }
//destructor
~MyString()
{
//free the array
delete[] data;
delete[] data_array_c_str;
};
const char* _data() const
{
return data;
}
const char* c_str() const//available only after MyString was created
{
MyString *ptr = const_cast<MyString*>(this);
ptr->data_array_c_str = new char[data_length + 1];
copy(data_array_c_str, data_length, 0);
data_array_c_str[data_length] = '\0';
return data_array_c_str;
}
private:
size_t data_length;
char* data;
char* data_array_c_str;
};
The problem is that after the "hrl" is assigned to mystr1 it calls the destructor trying to delete the private data pointer and the compiler breaks.
Can you help me how to fix it? Thanks