mardi 29 décembre 2020

Why I am getting different output in Visual Studio 2019 and on g++11 for the rvalue reference implementation in the following code? [duplicate]

I was trying out an example for rvalue reference in a copy constructor as shown in below code but the output are different on different compilers and able to understand why this difference is coming as this rvalue thing is the concept of c++11 and onwards.

#include<iostream> 
using namespace std;

class Test
{
    /* Class data members */
    int x{10};
public:
    Test(Test&& t) { cout << "copy constructor called" << endl;
    x = 20;
    }
    Test() { cout << "constructor called" << endl; }
    void print() {
        cout << x << endl;
    }
};

Test fun()
{
    cout << "fun() Called\n";
    Test t;
    return t;
}

int main()
{
    Test t1;
    t1.print();
    Test t2 = fun();
    t2.print();
    return 0;
}

Output in Visual Studio 2019:

constructor called
10
fun() Called
constructor called
copy constructor called
20

Output in gcc c++17 compiler:

constructor called                                                                    
10                                                                                    
fun() Called                                                                          
constructor called                                                                    
10 

Why this difference is coming?

Aucun commentaire:

Enregistrer un commentaire