1

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?

  • 3
    `Test(Test&& t) { cout << "copy constructor called" << endl;` -- That's a move constructor, not a copy constructor. – PaulMcKenzie Dec 29 '20 at 20:25
  • Also, if you compiled a release version in Visual Studio, you will see the output is different. This is what the duplicate link is referring to. – PaulMcKenzie Dec 29 '20 at 20:31
  • Thank you @PaulMcKenzie but why on gcc c++17 it was not called for `Test t2 = fun();` – deep_purohit Dec 29 '20 at 20:31
  • 1
    Because the compiler is smart not to create the extraneous copy? The issue is that you're trying to predict when (and where) a copy is going to be made. Unless it is a case where the compiler *must* remove the copy (as per C++11), you really can't predict for sure if the compiler will actually invoke the copy constructor. The Visual Studio debug versus release version is a classic case where predictions fall short. – PaulMcKenzie Dec 29 '20 at 20:35
  • Thank you @PaulMcKenzie now its clear. – deep_purohit Dec 29 '20 at 20:37

0 Answers0