+ 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?
5 Réponses
+ 1
Also how allocation happens for extra memory block required to use reference count in case of make_unique assigned to shared_pointer
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;
}
0
I think so
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 ?
0
should work btw thx