从数组的共享指针访问共享指针

Accessing shared ptr from shared ptr of array

我有将一些值复制到我将传递的对象的功能。

所以,像这样的东西

void functionReturnObjects(int* ptr);

我会像这样调用上面的函数

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

现在,我想从上述10个共享ptr中取出单独的共享ptr,并想单独复制或与其他共享ptr共享。

所以像

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

基本上我想在不分配新内存的情况下将所有权从 10 个共享指针转移到新的个人共享指针。

如果问题不清楚,请告诉我。

使用 std::shared_ptr's aliasing constructor(重载 #8):

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

这将使 newCopysp 共享使用 new int[10] 创建的整个数组的所有权,但 newCopy.get() 将指向所述数组的第二个元素。

在 C++17 中,如果您碰巧发现它更具可读性,它可以看起来像下面这样:

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