0
#include <iostream>

using namespace std;

struct foo{
    int x;
    double y;
    double z;

    foo(int x_,double y_,double z_)
    {
        x = x_;
        y = y_;
        z = z_;
    }
    foo(const foo& f){
        cout<<"foo copy for const ref called"<<endl;
        x = f.x;
        y = f.y;
        srand((unsigned ) time(nullptr));
        int z_ = rand();
        z = z_;
        cout<<f.x<<endl;
    }
    foo(foo&& f) {
        cout<<"foo copy for right ref called"<<endl;
        x = f.x;
        y = f.y;
        srand((unsigned ) time(nullptr));
        int z_ = rand();
        z = z_;
        cout<<f.x<<endl;
    }
};

int main()
{
    srand((unsigned ) time(nullptr));
    int rand_ = rand();
    foo f_(foo(rand_, 2, 3));
    cout<<f_.x<<' '<<f_.y<<' '<<f_.z<<endl;
}

I run the above code in gcc, and got the following output:

21862 2 3

I was expecting than the foo(foo&& f) will be called, but out of my expect, none of the copy constructors was called, and f_.z was set to be 3, I expect it to be a random value. why is none of the copy constructors being called?

Lucy
  • 33
  • 4
  • 1
    Copy/move ellision: https://en.cppreference.com/w/cpp/language/copy_elision – UnholySheep Dec 04 '22 at 12:17
  • 1
    C++ requires (as of C++17) **copy elision**. If a copy constructor has side-effects, those side-effects (such as `cout`) may not occur. C++ **expects** constructors to do a certain semantic (and *not* do side-effect things; lots of programmers forget that — including myself from time to time), which entails allowing for **copy elision**. – Eljay Dec 04 '22 at 12:20
  • See [dupe1](https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization), [dupe2](https://stackoverflow.com/questions/72253869/shouldnt-there-be-a-copy-ctor-invocation-here-elision-disabled-no-named-retur) and [dupe3](https://stackoverflow.com/questions/38043319/how-does-guaranteed-copy-elision-work). – Jason Dec 04 '22 at 12:41

0 Answers0