dimanche 3 juin 2018

c++ fonction call the destructor immediatly after

In the first main we will call the copy constructor for the initialisation of the two objects c and d. Then we will call the first = operator in my class then the destructor is called twice for the two objects and the output is I4I5c5d5d5

For the second main, we call the default constructor, then the copy for constructor for 5 and then we call the second operator in my class and at the end of the second operator the destructor is directly called.

I don't understand why in the first operator= the destructor is not called after the use of the operator and why in the second operator= the destructor is immediatly called after the use of the second operator...

thank you for your help and sorry for my english

#include <iostream>

using namespace std;

class C {

  int i;

 public:


   C() : i(0)                  { cout << "D" << i; }

   C(int _i) : i(_i)           { cout << "I" << i; }

   C(const C& _c) : i(_c.i)    { cout << "C" << i;  }

   C& operator= ( const C& _c) { i = _c.i; cout << "c" << i; return *this; }

   C(C&& _c) : i(_c.i)         { cout << "M" << i; _c.i = 0; }

   C& operator= (C&& _c)       { i = _c.i; cout << "m" << i; _c.i = 0;
                                return *this; }

   ~C()                        { cout << "d" << i;  }
};


int main() {

  C c = 4;
  C d = 5;
  c = d;
}

/* int main() {
  C c;
  c = 5;
  } */

Aucun commentaire:

Enregistrer un commentaire