I've illustrated the problem with comments in the below code:
class MyClass //Some string-like class that encapsulates a dynamic char array.
{
public:
MyClass(unsigned int size)
{
data = new char[size];
}
char* GetCharArray() //In places where passing the raw array is needed, I call this method, but I want to create a separate char array and not touch the original one.
{
char* temporary = new char[size + someNumber];
for(int i = 0; i < size; i++)
{
temporary[i] = data[i];
}
DoSomeOperationForRemainingCharacters(temporary);
return(temporary);
}
private:
char* data;
unsigned int size;
};
void SomeFunc(char* c);
int main()
{
MyClass string(50):
SomeFunc(string.GetCharArray()); //A new char array is allocated here, but it is
// never deleted. If I return a templated pointer wrapper that wraps the array
// and deletes it in the destructor, the wrapper dies at the end of
// GetCharArray(), so by the time it's passed to SomeFunc(), the char array is
// already deleted. What else can I do?
}
Maybe I need to make some small mini-garbage collection system?