is it possible to convert shared_ptr<int> to shared_ptr<int*> | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

is it possible to convert shared_ptr<int> to shared_ptr<int*>

Hi Please refer attached code: https://code.sololearn.com/c9A251A2A19A/#cpp we can always create shared_ptr<int*> as per test_1 function. Question is whether it is allowed to get shared_ptr<int*> from shared_ptr<int> by any means ? My trial fails as per function test_2...

14th Feb 2021, 1:48 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Answers
+ 1
Hi Ketan, I have tried to do the same, but it seems creating shared pointer from raw pointer is no bueno, found the following thread - https://stackoverflow.com/questions/33830765/to-avoid-creation-of-stdshared-ptr-from-raw-pointers
25th Feb 2021, 6:44 AM
Akib
Akib - avatar
+ 1
I haven't found any case for this to do, so I am not sure if its a good idea or even possible to do. Making int*, from <int> doesn't really help us since it doesn't increase the counter. Or you could use a weak pointer if that's the case. When the counter goes to zero <int*> will point to a memory that has already been freed, so I think that's why getting<int*> from <int> is not allowed either.
26th Feb 2021, 6:16 AM
Akib
Akib - avatar
0
Hi Akib , thanks for this ... yes , It's not a good thing to mix raw and smart pointer... Once we pass <int> as template to smart pointer, object would behave like a pointer and we access member through -> operator... Now question is can we have any link of smart pointer object of type int and int*? Generally , int and int* is related to address of variable , but here both of them are template type of a class object ... So is it possible to convert or it's very weired thing I am trying to figure out?
25th Feb 2021, 3:37 PM
Ketan Lalcheta
Ketan Lalcheta - avatar