将shared_ptr分配给数组的偏移量

u3l*_*u3l 10 c++ arrays reference-counting shared-ptr

假设我有一个shared_ptr数组:

std::shared_ptr<int> sp(new T[10], [](T *p) { delete[] p; });
Run Code Online (Sandbox Code Playgroud)

一个方法:

shared_ptr<T> ptr_at_offset(int offset) {
    // I want to return a shared_ptr to (sp.get() + offset) here
    // in a way that the reference count to sp is incremented...
}
Run Code Online (Sandbox Code Playgroud)

基本上,我要做的是返回一个新的shared_ptr,增加引用计数,但指向原始数组的偏移量; 我想避免在调用者在某个偏移处使用数组时删除数组.如果我回来sp.get() + offset可能会发生,对吗?我认为初始化一个新shared_ptr的包含sp.get() + offset也没有意义.

C++的新手,所以不确定我是否正确接近这个.

chr*_*ris 17

您应该能够使用别名构造函数:

template< class Y > 
shared_ptr( const shared_ptr<Y>& r, element_type* ptr ) noexcept;
Run Code Online (Sandbox Code Playgroud)

这与给定的共享所有权shared_ptr,但确保根据那个清理,而不是你给它的指针.

shared_ptr<T> ptr_at_offset(int offset) {
    return {sp, sp.get() + offset};
}
Run Code Online (Sandbox Code Playgroud)