2
#include <iostream>

class studant {
    public:
    studant () {
        std::cout<<"studant"<<std::endl;
    }
    studant(const  studant& a) {
        std::cout<<"copy studant (&)"<<std::endl;
    }
   studant(studant&& a) {
        std::cout<<"move studant (&)"<<std::endl;
    }
    studant maximum () {
        studant c1;
        return c1;
    }
};
studant create () {
     studant c1;
    return c1;
}
int main()
{
    studant c2;
    studant c3=c2.maximum ();
    studant c4=create ();
}

please see the above code why "studant c3=c2.maximum ()" and "studant c4=create ()" is not call the copy or move constructor. please explain me.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278

1 Answers1

1

This is because the RVO (Return Value Optimization). studant c3=c2.maximum () calls maximum(), the compiler knows the c1 inside maximum() will be returned and then assigned to c3, and then c1 will discarded. The compiler is smart enough to create just one instance of studant to avoid the assignment. That means c1 inside maximum() is the same instance as c3.

This is same for 'c4' and c1 in function 'create()'.

Tiger Yu
  • 744
  • 3
  • 5
  • This is a correct answer of why this would happen if optimizations are enabled. – NadavS May 02 '20 at 09:09
  • 1
    @NadavS For future readers: on a conforming C++17 compiler, RVO occurs regardless of whether optimization are enabled. – L. F. May 02 '20 at 09:11