vendredi 9 juin 2017

C++ Move semantics with object having integer member

#include<iostream>
#include<stdio.h>

using namespace std;
class Test
{    
   public:
       string n;
       Test():n("test") {}  
};

int main()
{
    Test t1;  
    std::cout<<"before move"<<"\n";
    std::cout<<"t1.n=" << t1.n<<"\n";
    Test t2=std::move(t1);

    std::cout<<"after move"<<"\n";
    std::cout<<"t1.n="<<t1.n<<"\n";
    std::cout<<"t2.n="<<t2.n<<"\n"; 

    return 0;
}

Output of the above program produces below result

before move t1.n=test after move t1.n= t2.n=test

Understood that, after moving the object t1 to t2, value of t2.n results as empty string

But the same concept move concept doesn't work with integer.

#include<iostream>
#include<stdio.h>

using namespace std;

class Test
{

    public:
        int n;
        Test():n(5) {}  

};

int main()
{
    Test t1;  
     std::cout<<"before move"<<"\n";
     std::cout<<"t1.n=" << t1.n<<"\n";
     Test t2=std::move(t1);

     std::cout<<"after move"<<"\n";
     std::cout<<"t1.n="<<t1.n<<"\n";
     std::cout<<"t2.n="<<t2.n<<"\n"; 

     return 0;
}

Output of the above program produces below result

before move t1.n=5 after move t1.n=5 t2.n=5

After moving the object t1 to t2, i expected the value of t2.n as 0 but the old value still exists.

Can someone please explain the concept behind this behavior.

Aucun commentaire:

Enregistrer un commentaire