gpt4 book ai didi

c++ - 从数组的共享指针访问共享指针

转载 作者:行者123 更新时间:2023-11-30 02:29:12 27 4
gpt4 key购买 nike

我有一个函数,可以将一些值复制到我要传递的对象。

所以,像这样的东西

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]);

关于c++ - 从数组的共享指针访问共享指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39820362/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com