Why my object still gets copied when I tried to return a reference

  • A+
class Obj { public:     Obj(int aa, int bb): a(aa), b(bb) {}     Obj(const Obj& o) {a = o.a; b = o.b;std::cout << "copying" << std::endl;}     Obj(Obj&& o) {a = o.a; b = o.b;std::cout << "moving" << std::endl;}     int a;     int b; }; const Obj& Min(const Obj &o1, const Obj &o2) {     if (o1.a > o2.a) {         return o1;     } else {         return o2;     } } int main() {     using namespace std;      auto o1 = Obj(1,1);     auto o2 = Obj(2,2);     auto res = Min(o1, o2);      cout << res.a << endl;     res.a = 100;     cout << o1.a << endl;     cout << o2.a << endl;      return 0; } 

The program still prints a word copying which indicates that the copy constructor is activated. Where is the constructor called then ? Why the function does not return a reference of o1 so that modifying the value of res will also changing the value of o1 ?


The copy is done in the statement:

auto res = Min(o1, o2); 

Min() return type is const Obj&. The auto above will be deduced to Obj, not const Obj& (i.e., res type will be Obj). res, which is an object, is initialized by means of the copy constructor (i.e., Obj::Obj(const Obj&)), therefore a copy construction takes place.

If you write instead:

auto& res = Min(o1, o2) 

res will be of type const Obj& and no copy construction takes place there, since res will be a reference, not an object.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: