[Solved] Difference between , and ;?


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:

  1. 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_;
}
  1. this.tiulo_ = rhs.titulo_ This means that both the l1 and l3 objects point to the “Fundamentos de C++” string that was dynamically allocated by l1‘s constructor
  2. l3.~Libro() is called implicitly as l3 leaves scope which will call delete [] titulo_ destroying the “Fundamentos de C++” dynamically allocated member of l3 which is also l1‘s titulo_ member.
  3. l1.~Libro() is called implicitly as well, which will call delete [] titulo_ however this time that member was deleted by l3 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";

Live Example

2

solved Difference between , and ;?