lundi 9 août 2021

Direct VS Copy Initialization in C++

Hi i am trying to understand how direct and copy initialization works and so have this example whose output i am unable to understand.

class DeletedCopy
{   public:
    
        DeletedCopy(const DeletedCopy&) = delete;
        DeletedCopy(DeletedCopy&) = delete;
        DeletedCopy()
        {
            std::cout<<"DeletedCopy Default constructor "<<std::endl;
        }
        DeletedCopy(DeletedCopy &&) 
        {
            std::cout<<"DeletedCopy move constructor"<<std::endl;
            
        }
};
class NAME
{
    private:
        std::string name;
        DeletedCopy temp;
    public:
        NAME() = default;
        NAME(const NAME& _name): name(_name.name)
        {
           std::cout<<"Copy constructor ran"<<std::endl; 
        }
        
        
        NAME(DeletedCopy d): name("v"),temp(std::move(d))
        {
            
          std::cout<<"explicit constructor NAME"<<std::endl;
        }
       
};
int main()
{
   cout << "Hello World" << endl; 

   
   NAME name3 = DeletedCopy();//this works and prints 3 lines on screen.
   NAME name4(DeletedCopy());//this doesn't print anything on console. Why doesn't this print anything. Is this statement UB
   
   return 0;
}

In this example when i used direct initialization, nothing is printed on the console. While if i use copy initialization then i get 3 lines printed on the console. Why isn't the direct initialization case working.

Aucun commentaire:

Enregistrer un commentaire