For classes that have dynamic memory.
Code:
class string
{
private:
char* data;
size_t len;
};
If you let the compiler create a default copy constructor then it will copy the pointer for data over. You don't want this. The default copy constructor might look like this:
Code:
string::string(const string& str) {
data = str.data;
len = str.len;
}
They would be sharing the same block of memory.
What you want is something like this:
Code:
class string
{
private:
char* data;
size_t len;
public:
string(const string& str) {
len = str.len;
data = new char[len];
memcpy(data, str.data, len);
}
};