I have class, but I don't know how I should handle freeing its member string, when I don't have a prior knowledge of how the string would get allocated. So say that I created a class C1,
Code:
class C1
{
public:
c1() : str(NULL) {};
~c1() { delete [] str };
char* str;
};
Client 1 uses the class in following way
Code:
int main(...)
{
C1 c1;
c1.str = new char[256];
strcpy(c1.str, "here is some string");
return 0;
}
Client 2 uses the class in following way
Code:
int main(...)
{
C1 c1;
c1.str = "here is some string";
return 0;
}
Of course for the case of client 2, when the class object goes out of scope, its destructor would attemp to "delete []" the constant string which is illegal.
How do you guys handle this kind of scenario? Is commenting to warn class users the only option, or would there other way of handling this programmatically?
Would 1) create a set public function 2) always copy strings clients pass to the object 3) delete [] the copied string from destructor the only option?