将shared_ptr分配给数组的偏移量

Assigning a shared_ptr to an offset of an array

本文关键字:数组 偏移量 分配 shared ptr      更新时间:2023-10-16

假设我有一个数组shared_ptr

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

还有一个方法:

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...
}

基本上,我试图做的是返回一个新的shared_ptr,该增加引用计数,但指向原始数组的偏移量;我想避免在调用方以某种偏移量使用数组时删除数组。如果我只是返回sp.get() + offset可能会发生这种情况,对吧?而且我认为初始化一个新shared_ptr以包含sp.get() + offset也没有意义。

C++新手,所以不确定我是否正确接近了这一点。

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

template< class Y > 
shared_ptr( const shared_ptr<Y>& r, element_type* ptr ) noexcept;

这与给定的shared_ptr共享所有权,但请确保根据该清理,而不是您给它的指针。

shared_ptr<T> ptr_at_offset(int offset) {
return {sp, sp.get() + offset};
}