rekkalmd
rekkalmd

Reputation: 181

Understanding the behavior of constructors in move, copy, assign semantics

Here is a minimal program which outputs C-tors & D-tors, also Move/Copy operations.

What is intriguing to me is that there is just one C-tor in output, despite there is three entities which are destroyed at the end of the scope (D-tors displayed).

So why there is just one C-tor displayed ? and how can we handle it (display them), or if there is a misunderstanding from my part, what should we know about that.

#include <iostream>

class Subject{

public:

    Subject(){
       std::cout<<"Default C-tor"<<std::endl;

    }
    Subject(int data):mdata(data){
        std::cout<<"C-tor"<<std::endl;
    }

    virtual~Subject(){

        std::cout<<"D-tor"<<std::endl;
    }


    Subject(Subject const& subject): mdata(subject.mdata){
         std::cout<<"Object copied"<<std::endl;
   }

    Subject& operator=(Subject const& subject){
          if(this != &subject){
              mdata=subject.mdata;
         std::cout<<"Object copied"<<std::endl;
          }
          return *this;
    }

        Subject(Subject const&& subject): mdata(std::move(subject.mdata)){
         std::cout<<"Object moved"<<std::endl;
   }

    Subject& operator=(Subject const&& subject){
          if(this != &subject){
              mdata=std::move(subject.mdata);
         std::cout<<"Object moved"<<std::endl;
          }
          return *this;
    }

    friend std::ostream& operator<<(std::ostream& out, Subject const& subject){

        out<<subject.mdata<<std::endl;

        return out;
     }

protected:
    int mdata;

};

int main()
{
   Subject subject{42};

   Subject copySubject{subject};

   Subject moveSubject = std::move(subject);

    return 0;
}

Noting that if i declare the copySubject and the moveSubject like :

   Subject copySubject{};

   Subject moveSubject{};

It will work by calling the Default Constructor.

Upvotes: 0

Views: 38

Answers (1)

eerorika
eerorika

Reputation: 238301

So why there is just one C-tor displayed ?

Because you used the converting int constructor once, when you direct initialised here:

Subject subject{42};

despite there is three entities which are destroyed

The other two objects were created using the copy constructor and move constructor respectively. Note how neither of these constructors displays "C-tor".

You've defined three variables, so it should hardly be surprising that three objects were created and destroyed.


P.S. Your move assignment and constructor don't actually move the member because you used a const reference as argument.

Upvotes: 1

Related Questions