#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.
This is because the RVO (Return Value Optimization).
studant c3=c2.maximum ()callsmaximum(), the compiler knows thec1insidemaximum()will be returned and then assigned toc3, and thenc1will discarded. The compiler is smart enough to create just one instance ofstudantto avoid the assignment. That meansc1insidemaximum()is the same instance asc3.This is same for 'c4' and
c1in function 'create()'.