+ 1

Assign unique pointer to shared pointer

Hi We can convert unique_ptr to shared pointer either by 1. Moving unique pointer to shared pointer as assignment [refer sp1 in code]. Isnt this assignment of unique pointer r value reference to shared pointer? 2. Assigning return value of make_unique to shared pointer [refer sp2 in code]. Isnt this assign of unique pointer to shared pointer ? make_unique returns only unique pointer. If so , (specially point 2), why can't i directly assign unique pointer to shared pointer in code below: https://code.sololearn.com/cePGcknx1ycJ I mean why sp3 fails to compile?

6th Apr 2022, 10:48 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 Respuestas
+ 1
Also how allocation happens for extra memory block required to use reference count in case of make_unique assigned to shared_pointer
2nd Apr 2023, 1:47 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
I dont know what you want to do but i know i have to do : #include <iostream> #include <memory> using namespace std; unique_ptr<int> getUniquePointer() { unique_ptr<int> up = make_unique<int>(); return up; } int main() { unique_ptr<int> up1 = getUniquePointer(); // Added '=' to assign the returned pointer unique_ptr<int> up2 = getUniquePointer(); // Added '=' to assign the returned pointer shared_ptr<int> sp1 = move(up1); // Added '=' to assign the moved pointer shared_ptr<int> sp2 = make_shared<int>(); // Changed to make_shared shared_ptr<int> sp3 = move(up2); // Changed to move instead of typecasting return 0; }
2nd Apr 2023, 1:06 PM
D1M3
D1M3 - avatar
0
I think so
2nd Apr 2023, 1:07 PM
D1M3
D1M3 - avatar
0
In my code for sp2, we are getting unique pointer by make_unique and same gets assigned to shared pointer sp2. If this works, why another unqiue pointer up2 is not assigned to shared pointer sp3 ? Either both (sp2 and sp3) should work or both should not work..right ?
2nd Apr 2023, 1:45 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
should work btw thx
2nd Apr 2023, 1:46 PM
D1M3
D1M3 - avatar