I have a question about object array allocation, the problem is this: I have a class called person :
class Person {
char* name;
int ID;
public:
Person(char* name = NULL, int ID = 0) :name(name), ID(ID) {};
}
and I'm trying to make an array of persons like so:
Person *pArr = new Person[size];
and after that I extract the data from a file (char* for string and int for ID) and I use for loop and the constructors to place the persons inside the loop like so:
for (int j = 0; j < size3; j++) {
pArr[j] = Person(Name, id);
}
after I finish my program I want to use the Destructor and free the allocated string that's stored inside the char* name, but when I add the Destructor it gets triggered right after the loops ends, every Person that's being created is destroyed immediately, I know its possible to make an array of pointers and allocated the person aswell, but in this assignment I'm suppose to do it like this, is there a right way to do it without triggering the destructor right away?
On this line:
You are creating a temporary
Person
object, and then assigning it to thepArr[j]
object.Person
has no explicit copy assignment operator defined, so the compiler auto-generates one for you, which simply performs a member-by-member copy of values from one object to another.When the temporary goes out of scope on the
;
, it is automatically destroyed. The compiler-generated assignment operator copied thename
pointer as-is to thepArr[j]
object, so ifPerson
has a destructor that frees itsname
, thepArr[j]
object will be left with a danglingname
pointer to freed memory.Your
Person
class is not following the Rule of Three:Since you want
Person
to have a destructor that freesname
, it also needs a copy constructor and a copy assignment operator so it can make copies ofname
for the destructor to free, eg:Now, back on this line:
The temporary will be copied to
pArr[j]
safely and properly. Just note that if you dynamically allocatedName
beforehand, you will now have to free it afterwards, sincePerson
makes its own internal copy.If you can change
char*
tostd::string
, then you don't have to worry about the compiler making default copies, sincestd::string
is compliant with the Rule of Three and will be copied properly: