【问题标题】:Accessing shared ptr from shared ptr of array从数组的共享 ptr 访问共享 ptr
【发布时间】:2016-10-02 18:40:38
【问题描述】:

我有将一些值复制到我将传递的对象的函数。

所以,像这样的事情

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 个共享指针转移到新的个人共享 ptr。

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

【问题讨论】:

  • 如果您的“个人”注视指针不与其他已注视指针共享所有权,那么您必须为其分配其他东西以共享其他指针未共享的内容。
  • 不,不要阅读“教程”。买一本合适的书。

标签: c++ c++14 shared-ptr shared-memory unique-ptr


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 2011-04-22
    • 1970-01-01
    • 2013-07-06
    • 2013-11-27
    相关资源
    最近更新 更多