+ 2

Ownership on move constructor with vector

Hi Refer below code and observe it's output : Between 0. And 1. In output, everything is fine... Object got constructed and copied which will result into destructing of two objects later at end...one for copy (in vector) and one for original (in main) Between 1. And 2. I have a query over here.... Temp object got created and obviously it is to be destroyed once push_back line is executed. So , one constructor and one destructor is fine. Now comes move constructor called in between. It is also expected... But question is that move constructor just transfer ownership so deleted that temp object due to destructor called is allocated to vector... Isn't it? Feel free to ask for any further details on question.. my short query is that move constructor just transfer ownership and that owned object is deleted due to temp object type and hence vector has proper object or not now ? https://code.sololearn.com/cEUT4DecUEtZ/?ref=app

17th May 2021, 7:05 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Antworten
+ 1
Ketan Lalcheta you can consider move constructor as a copy constructor which removes the contents of original object after copying it's content to another, the object will still be destroyed as soon as it goes out of scope ( which is right after the function call for that temporary variable )
18th May 2021, 12:21 PM
Arsenic
Arsenic - avatar
+ 1
When you do " push_back(test()); " The following things happen :- 1) creation of an object of type "test" by default constructor ( let's call it "temp" ) 2) rvalue of the object is passed to push_back() function which then "steals" all its content and give it to the object at the end of the vector ( move operation or transferring ownership ) leaving poor "temp" soul-less. 3) upon returning from the function call "temp" goes out of scope and die ( call to destructor ) So yes, even though "temp" had to go though a short and sad life, you will be having a proper object at the end of your vector.
18th May 2021, 11:40 AM
Arsenic
Arsenic - avatar
0
Thank you Arsenic ... Getting what you are saying... But generally move constructor takes away ownership of one object to another and it's a single copy later on... So why two destructor gets called. Is this special case due to vector push back behaviour or is it due to temp object ?
18th May 2021, 12:06 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Thank you Arsenic .... It made clear to me... Object resources (not deleted till scope is over) are transferred when it is moved... This code depicts the same if anyone is interested to see... I just got confuse with the fact that moved object should not be used later on .... It was due to the fact that it doesnot hold any data , not because of same getting destroyed. Many thanks... https://code.sololearn.com/cdD67rtM3Nig/?ref=app
18th May 2021, 6:52 PM
Ketan Lalcheta
Ketan Lalcheta - avatar