EDIT Looks like I didn't explain myself in a good way. My question was not about the Rule of 3, or how to implement it in a good way. My question is why when using comma the destructors are called after complete the sequence and not when the variables leave the scope, I mean, the objets are only destroyed when all the functions between comma have finished, you can see it adding a cout to the destructors.
In this 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 copy constructor is not defined and the default copy constructor provide by the compiler is not valid in this case, the execution is correct and It shows the right information in the calls to mostrar(l1), mostrar(l2), mostrar(l3);.
However, if we use mostrar(l1); mostrar(l2); mostrar(l3); instead, we would have the expected error, the last call wouldn't show correctly the last call, because the copy haven't been done properly.
Do you know what is the diference between use , and ;? Why this code is working when you use ,?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…