I am using a class from a library. Let it be A, and it has a character pointer "token"
My code:
void someFunction()
{
A a;
cout<<a.token;
anotherFunction(a);
cout<<a.token; // line 4: now token became invalid [1]
}
void anotherFunction(A copyOfA);
{
// doing something
} // on exit destructor of copyofA will be called
[1] Why did it become invalid: class A is as follows:
class A
{
char *token;
public:
A()
{
token = GetRandomToken(); // GetRandomToken will return a 'new Char' array
}
~A()
{
if(token != NULL)
{
delete[] token; // it is A's responsibility to delete the memory it created
token = NULL;
}
}
};
in anotherFunction
when the destructor of copyOfA is called token
got deleted. So at line 4, token is invalid because both a.token and copyOfA.token both pointing to same address.
What is the solution, in following case:
case 1: class A
is in a given library: So I can't modify it.
case 2: if I can modify class A
: What will be the good way to handle this?
I know, if anotherFunction is called by passing reference, I won't have hit this problem. But what if I have to keep a copy of the object at some point?
Check sample code here: https://ideone.com/yZa4k4