Chapitre 11 : Règle des 3

#include<cstdlib>

class Tab10{
  int* t = nullptr;
  public:
    Tab10(){
      t = (int*) malloc(10 * sizeof(int));
    }

    int& at(int i){
      if (i<0 || i>9) exit(1);
      return this->t[i];
    }

    ~Tab10(){
      free(this->t);
    }

    Tab10(const Tab10& s){
      this->t = malloc(10 * sizeof(int));
      if (this->t == nullptr) exit(1);
      int i;
      for (int i=0; i<10;i++) this->t[i] = s.t[i];
    }

    const Tab10& operator=(const Tab10& s){
      if (this == &s) return;
      int i=0;
      for (i=0; i<10; i++) this->t[i] = s.t[i];
      return *this;
    }

void g(Tab10 c);

void f(){
  Tab10 ob;
  ob.at(0) = 1;
  Tab10 ob1{ob}; //Tab10 ob1 = ob; // appel au constructeur par copie
  g(ob); // appel au constructeur par copie
  o = ob1; //ob.operator=(ob1);
  ob = ob1 = ob2; //implicitement : ob = (ob1 = ob2);
}

Bilan

Quelquefois les comportements du destructeur, du constructeur par copie, et l'opérateur = (affectation) construits par défaut, sont non souhaitables, il faut les (ré-)écrire.

Souvent on doit en réécrire un des trois, il faut réécrire les deux autres.