I hope my question has not been posted in the past (I searched but I guess I'm not using right keywords, couldn't find anything).
I was wondering, is there a way to create a shared_ptr
without copying the instance ? I mean, I saw that make_shared
recreate what we pass as argument. So I tried to do it in class A
with shared_ptr(this)
, but I'm not sure it works as expected.
What does shared_ptr(raw pointer)
exactly does ? Does it just stores the pointer or does it create a new instance using the copy constructor and storing its pointer ?
Thanks for your answer
I think you are confused as to how pointers behave...maybe? It is hard to decipher what you are asking.
I will take a stab with the following explanation though:
std::shared_ptr<int> mySharedPtr(new int(5));
creates one and only one instance of an int.
int * myPointer = new int(5);
std::shared_ptr<int> mySharedPtr = myPointer;
also creates one and only one instance of an int.
int * myPointer = new int(5);
std::shared_ptr<int> mySharedPtrA = myPointer;
std::shared_ptr<int> mySharedPtrB = mySharedPtrA;
also creates one and only one instance of an int.
std::shared_ptr<int> mySharedPtrA = std::make_shared<int>(5);
std::shared_ptr<int> mySharedPtrB = mySharedPtrA;
also creates one and only one instance of an int.
In all of those cases, the value of the int is 5, there is one instance, and the pointer to the int is being passed around.
The int is not being passed around, the pointer to the int is. The int is not being copied, the pointer to the int is being copied.
A someInstance;
auto sptr = std::make_shared<A>(someInstance)
Yes, in this case sptr
will be new shared_pointer instance with newly created copy of someInstance
(if A
class has the public copy constructor defined - implicit or explicit).
What std::make_shared(...)
does? It "tries" to match proper constructor basing on given parameters list. In this case, you pass `A const&' which will be matched to copy constructor.
Summarizing:
std::shared_ptr<T>(...)
creates std::shared_ptr
from:
std::unique_ptr<T>
std::make_shared<T>
creates std::shared_ptr<T>
using T
constructorIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With