EDIT: This is not a question about dynamic memory handling, it is a question about the compiler's behavior when function calls are separated by commas. This is an example of a book to demonstrate this behavior. Destructors are called when the end of the line is reached, at the ; , not when variables go out of scope. This can be checked by couting the destructor of the book class. That is, during show(l1), show(l2), show(l3) no destructor is called, neither from the local variables of the functions nor from those of the main, but all are called once it has finished the execution of the three functions.
The question is, why does the compiler not call the destructors during execution of display(l1), display(l2), display(l3), when local variables go out of scope (expected behavior), and instead call all destructors when execution reaches the ;, i.e. when display(l3) is executed, no destructor has been called yet, so by using a comma, the information is still there when l3 wants to access it.
In the following example,
#include <iostream>
#include <cstring>
using namespace std;
class Libro {
char* titulo_; int paginas_;
public:
Libro() : titulo_(new char[1]), paginas_(0) {*titulo_= 0;}
Libro(const char* t, int p) : paginas_(p) {
titulo_ = new char[strlen(t) + 1];
strcpy(titulo_, t);
}
~Libro() { delete[] titulo_; }
void paginas(int p) { paginas_ = p; }
int paginas() const { return paginas_; }
char* titulo() const { return titulo_; }
};
void mostrar(Libro l) {
cout << l.titulo() << " tiene " << l.paginas() << " paginas" << endl;
}
int main() {
Libro l1("Fundamentos de C++", 474), l2("Por Fin: C ISO", 224), l3;
l3 = l1;
mostrar(l1), mostrar(l2), mostrar(l3);
}
Despite the fact that the copy constructor is not implemented and the constructor generated by the compiler does not work correctly (it only copies the address to the memory block of title_ ), when executed it correctly displays the information on the screen, with the function show. However, when using ; instead of , , the memory access in the show(l3) call is incorrect, and the information is not displayed properly, since, as expected, the copy was not performed correctly. Do you know what the difference is between using ; and , ?