Bonjour, j'ai écrit ce code pour comprendre comment se passe les différentes constructions (default/copie/move) :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
 
int osef(int); //fonction onsenfout (randomlike)
void print(const string & m=""){cout<<m<<endl;} //print quoi
 
class MyInt{ 
private:
  int val; 
  string c; // Pour le nom de la variable dans le main et suivre les différentes étapes lors de passages/retour par fonctions.
  void print(const string& Opt="") const { // Fonction d'affichage lors des constructions et operations d'assign
  ostringstream out;
  out<< Opt <<" ("<<c<<" = "<<val<<")";
  ::print(out.str());
}
 
public:
  MyInt() : val{0}, c{"d"} {
    print("Constr Defaut");  //Aff
  }
 
  MyInt(const int& i, const string& e) : val{i}, c{e} {
    print("Constr Init"); //Aff
  }
 
  MyInt(const MyInt& I) : val{I.val}, c{I.c} {
    c+="(copy)";
    print("Constr Copy"); //Aff
  }
 
  MyInt(MyInt&& I) : val{I.val}, c{I.c} {
    c+="(cmovedIN)";
    I.c+="(cmovedOUT)";
    I.val=::osef(I.val);
    print("Constr Move"); //Aff
  }
 
  MyInt& operator =(const MyInt& I) {
    c="E_"+I.c;
    val=I.val;
    print("Copy Assign"); //Aff
    return *this;
  }
 
  MyInt& operator =(MyInt&& I){
    val=I.val;
    c=I.c+"(emovedIN)";
    I.c+="(emovedOUT)";
    I.val=osef(osef(I.val));
    print("Move Assign"); //Aff
    return *this;
  }
 
  friend MyInt operator +(const MyInt& , const MyInt& );
 
  ~MyInt() {print("Destr");}
};
MyInt operator +(const MyInt& A, const MyInt& B)
{
  MyInt res(A.val,"res("+A.c+"+"+B.c+")");
  res.val+=B.val;
  return res;
}
Associé a un main que je commente // avec la sortie console et /* ce a quoi je m'attends et/ou pourquoi ca me pose probleme */.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
MyInt A(2,"A"); //  Constr Init (A = 2)
                       /*    OK    */
 
MyInt B(4,"B"); // Console : Constr Init (B = 4)
                        /*     OK       */
 
MyInt C = A + B;     // Constr Init (res(A+B) = 2)
                              /*  En partie OK : Appel au constructeur de res dans MyInt::operator+, mais le problème c'est que c'est tout...
                               *  je m'attendais à un appel de MyInt::MyInt(Myint&&) pour construire C 
                               *  ainsi qu'a un appel du destructeur de la variable locale res dans MyInt::operator+ 
                               *  */
 
print("**** Fin *****"); //**** Fin ***** 
                              /* ... */
                              //Destr (res(A+B) = 6)
                              /* Ok, détruit C */
return 0;