+ 1

Why conversion from unique_ptr to shared_ptr is not consistent

Refer code below: https://www.sololearn.com/compiler-playground/coCYxTNV4H1Y My query is regarding conversion from unique_ptr to shared_ptr. Dev1 is shared_ptr and still works even if I had done make_unique. Then why Dev3 is not compiling even though Dev2 is of make_unique.? https://code.sololearn.com/coCYxTNV4H1Y/?ref=app

16th Sep 2023, 8:33 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Respuestas
+ 1
Ketan 👋, Dev1 works cuz, you use 'make_unique' to create a 'unique_ptr',and then you assign it to a 'shared_ptr'. when you assign a 'unique_ptr' to a 'shared_ptr', ownership is transfeered from the 'unique_ptr' to the 'shared_ptr'. This means that the object is now managed by the 'shared_ptr', and its lifetime will be determined by the last 'shared_ptr' that goes out of scope or explicitly reset. Dev2 is a unique_ptr to an IEmployee object. you cannot directly assign it to a 'shared_ptr' cuz the ownership model is different. try use std::move(Dev2)
16th Sep 2023, 3:19 PM
Amine Laaboudi
Amine Laaboudi - avatar
+ 2
Ketan Lalcheta Your code link is not clickable.
16th Sep 2023, 8:35 AM
JAY
JAY - avatar
+ 1
I dont know why web version of code link does not work on mobile app. I have added link now from mob as well. Should be fine now
16th Sep 2023, 8:41 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
16th Sep 2023, 4:32 PM
Ketan Lalcheta
Ketan Lalcheta - avatar