将shared_ptr分配给数组的偏移量
Assigning a shared_ptr to an offset of an array
假设我有一个数组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};
}
相关文章:
- 张量(多维数组)是树前瞻数据的有效存储类型吗?
- 为什么我不能将 op 结果乘以常量特征张量数组
- 在 tensorflow c++ api 中,如何从张量中保存图片或数组
- 如何将张量转换为图像数组
- C++ 数组将所有值调整相同的量
- 将shared_ptr分配给数组的偏移量
- C++ 函数返回带有偏移量的数组
- C++ 将部分数组(在某些偏移量)转换为其他类型
- 将数组的内容从偏移量写入c++向量
- 两个相同大小(和长度)的数组是否具有相同的元素偏移
- 严格的混叠警告,创建对无符号字符数组 + 偏移量的uint32_t引用
- 从偏移量中删除数组
- 更快地将数组中的数据复制到目标,同时应用缩放或偏移因子
- 取消引用运算符给出的结果与具有 void* 的数组偏移运算符不同
- 给定元素数组、子列表的偏移量和长度的有效部分约简
- 索引到信号量数组中
- 信号量数组初始化为NULL,seg错误
- 多维数组(或张量)和向量的乘积
- c++ pthreads返回数组偏移量
- 指向成员(偏移量)的指针数组作为C++中的模板参数