You have not written a copy constructor or a copy assignment operator. The Rule of 3 tells us that anytime a destructor has been written, the copy assignment operator and copy constructor should be as well. You haven’t written either so let’s look at what happens:
l3 = l1
in this line the implicitly defined copy assignment operator is called which will be defined like this:
Libro& Libro::operator=(const Libro& rhs) {
this.tiulo_ = rhs.titulo_;
this.paginas_ = rhs.paginas_;
}
this.tiulo_ = rhs.titulo_
This means that both thel1
andl3
objects point to the “Fundamentos de C++” string that was dynamically allocated byl1
‘s constructorl3.~Libro()
is called implicitly asl3
leaves scope which will calldelete [] titulo_
destroying the “Fundamentos de C++” dynamically allocated member ofl3
which is alsol1
‘stitulo_
member.l1.~Libro()
is called implicitly as well, which will calldelete [] titulo_
however this time that member was deleted byl3
leaving scope, for a deleted pointer:
Passing it to a deallocation function (double-delete) is undefined behavior
So your issue is not the ,
versus the ;
but the double-delete that results from not following The Rule of 3.
If I may though, rather than suggesting you create a copy constructor and copy assignment operator, I’d suggest you do away with Libro
and use string
in a `pair your code would be as simple as this:
pair<string, int> l1 = make_pair("Fundamentos de C++"s, 474), l2 = make_pair("Por Fin: C ISO"s, 224), l3;
This will of course require you to explicitly output each member, for example:
cout << l1.first << " tiene " << l1.second << " paginas\n" << l2.first << " tiene " << l2.second << " paginas\n" << l3.first << " tiene " << l3.second << " paginas\n";
2
solved Difference between , and ;?