jeudi 28 avril 2016

When move constructor will get called in C++11?

I am not able to understand why why move constructor is not getting called while move assignment is able to while if I use move function in Line X , it used to call the move constructor . Can anybody tell what will be the way or syntax to call the move constructor .

#include <iostream>
#include <cstring>
#include <algorithm>
#include <memory>
using namespace std;
class String
{
    char *s;
    int len;
    public:
    String():s(nullptr),len(0){ cout<<"Default "; }
    String(char *p)
    {
        if(p)
        {
            len = strlen(p);
            s = new char[len];
            strcpy(s,p);
        }
        else
        {
            s = nullptr;
            len = 0;
        }
        cout<<"Raw ";
    }
    String(String &p)
    {
        if(p.s)
        {
            len = strlen(p.s);
            s = new char[len];
            strcpy(s,p.s);
        }
        else
        {
            s = nullptr;
            len = 0;
        }
        cout<<"Copy ";
    }
    String & operator = (const String & p)
    {
        if(this != &p)
        {
            delete []s;
            s = nullptr;
            len = 0;
            if(p.len)
            {
                len = p.len;
                s = new char[len];
                strcpy(s,p.s);
            }
        }
        cout<<"Assignment ";
        return *this;
    }
    String( String && p):s(nullptr),len(0)    // move constructor 
    {
        len = p.len;
        s = p.s;
        p.s = nullptr;
        p.len = 0;
        cout<<"Move Copy ";
    }
    String & operator = (String && p)       // move assignment
    {
        if(this != &p)
        {
            delete []s;
            len = 0;
            s = nullptr;
            if(p.len)
            {
                len = p.len;
                s = p.s;
                p.s = nullptr;
                p.len = 0;
            }
        }
        cout<<"Move Assignment ";
        return *this;
    }
    ~String() { delete []s; cout<<"Destructor \n"; }
    void show() { cout<<s<<endl; }
};
int main()
{
   String s1("Something ");
   String s2(s1);
   s1.show();
   s2.show();
   String s4(String("Nothing "));       // Line X
   s4.show();
   String s5;
   s5 = String(s2);
   s5.show();
   return 0;
}

OUTPUT:

Raw Copy Something Something Raw Nothing Default Copy Move Assignment Destructor Something Destructor Destructor Destructor Destructor

Aucun commentaire:

Enregistrer un commentaire