Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create shared_ptr without copying instance

Tags:

c++

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

like image 911
Megalovania Powa Avatar asked Mar 09 '23 10:03

Megalovania Powa


2 Answers

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.

like image 33
Christopher Pisz Avatar answered Mar 24 '23 23:03

Christopher Pisz


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:

    • other shared_ptr,
    • std::unique_ptr<T>
    • pointer of T,
    • (empty shared_ptr)
  • std::make_shared<T> creates std::shared_ptr<T> using T constructor
like image 108
Kuba Molski Avatar answered Mar 24 '23 23:03

Kuba Molski