I was wondering if I have to delete this pointer in example like this :
class Person
{
public:
Person(char *name) :_name(name) {}
// Is this delete necessary?
~Person() {
cout<<"Godbay Person"<<endl;
delete _name;
}
private:
char * _name;
}
This is pretty surely wrong in any case.
There are two possibilities:
The name is created on the free store exclusively for your object, and your object has to assume ownership. Then the name has to be deleted.
The name is not created on the free store (e.g. as a string litaral, which is quite possible), or some other object is managing the name, so your object should not assume ownership. Then any deletion would wreak havoc with your program.
So why do I say its wrong even in the first case? Because name
sounds like a string, not a single character, wich means name*
will point to an dynamically alocated array of characters. In that case, the correct way to delete it would be delete[] name
.
But: If possible, avoid using plain (char) pointers, for case 1. Use some memory management class instead (a string class or smartpointers), to get rid of the headaches of manually managing memory ownership. delete
and delete[]
should appear only seldom in your code except if you don't have access to up-to-date C++ compilers.