+ 3

Why copy constructor is not called

Please refer below code : I am calling get method which creates object and return by value. Current code output display ctor due to comstructor call from get method. Does this method provide copy of this object into main function? If so, why copy constructor is not called? https://code.sololearn.com/cAysQChE2XuK/?ref=app

12th May 2021, 3:14 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Réponses
+ 4
This is because of copy elison, which is a compiler optimisation technique where compiler can eliminate unnecessary copying of objects. situations where compiler must/may perform this optimisations is stated by language standards. This perticular case ( initialisation of your object ) comes under mendatoy elison via return value optimisation (RVO) where compiler is eliminating the temporary object created to hold the return value of constructor and thus removing the call to copy constructor. Know more about copy elison here👇 https://en.cppreference.com/w/cpp/language/copy_elision
12th May 2021, 3:49 PM
Arsenic
Arsenic - avatar
+ 1
The code didn't execute properly, but from what I can see, the program will call for the constructor. The reason the copy constructor is not called is because the copy constructor itself is a function with one parameter. You didn't call such function,so it didn't execute. If you wanted to call the copy constructor, the code would go something like this: Test obj1;//constructor Test obj2(obj1);//copy constructor Hope this helps :)
12th May 2021, 3:24 PM
Mihail
Mihail - avatar
+ 1
I got your point about copy constructor getting called when obj2 is constructed from obj1 I am confused on function return value. Get method calls constructor and this object is local and within the function itself. Now copy of the same is to be assigned to obj into main function...right ? In this copy , why copy constructor is not called
12th May 2021, 3:39 PM
Ketan Lalcheta
Ketan Lalcheta - avatar