eswaat eswaat - 24 days ago 4
C++ Question

Accessing shared ptr from shared ptr of array

I have function which is copying some value to objects i'll pass.

So, Something like this

void functionReturnObjects(int* ptr);

I'll call above function like this

std::shared_ptr<int> sp( new int[10], std::default_delete<int[]>() );
functionReturnObjects(sp.get()); => so this will copy int objects to sp.

Now, I want to take individual shared ptr from the above 10 and want to make separate copy or want to shared it with some other shared ptr.

So something like

std::shared_ptr<int> newCopy = sp[1] ==> This is not working I am just showing what I want.

Basically I want to transfer ownership from 10 shared pointer to new individual shared ptr without allocating new memory.

Please let me know if the questions is not clear.


Use std::shared_ptr's aliasing constructor (overload #8):

template< class Y > 
shared_ptr( const shared_ptr<Y>& r, element_type *ptr );
std::shared_ptr<int> newCopy(sp, sp.get() + 1);

This will make newCopy and sp share ownership of the entire array created with new int[10], but newCopy.get() will point to the second element of said array.

In C++17 this can instead look like the following if you happen to find it more readable:

std::shared_ptr<int> newCopy(sp, &sp[1]);